Automattic / juice

Juice inlines CSS stylesheets into your HTML source.
MIT License
3.12k stars 221 forks source link

How to change relative url paths in external CSS? #318

Open Marcus-Smallman opened 6 years ago

Marcus-Smallman commented 6 years ago

I am using Juice to try and inline font-awesome CSS.

Given I have a html file called 'test.html' which includes the following:

<link rel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/3.1.0/css/font-awesome.min.css">

And I then run the following juice command (which I ran at the following directory: C:\Users\admin\Desktop):

juice test.html test-out.html

I get the following error:

Error: The file C:\Users\admin\Desktop\https:\cdnjs.cloudflare.com\ajax\libs\font-awesome\3.1.0\font\fontawesome-webfont.eot was not found!

It is clear that the error states that it is trying to reference a file that does not exist locally, and so it shouldn't.

Now it appears the issue is related to the external css in that it references @font-face's relatively. Which (I think) means that when Juice tries to inline the css, it uses the local relative path, causing the the error.

I have tried using the --web-resources-relative-to and --web-resources-rebase-relative-to flags to see if this would fix the issue but they cause any other references to behave differently causing different errors.

I should also make it clear that I need to make this work without modifiying the html. Is there anything in Juice that I am blindly missing that would help me resolve this issue? or is it not possible to change the relative path of external file/css references

kevinleguillou commented 5 years ago

I encountered the same problem so if anybody needs the solution after all this time, here it is :

juice(html, {
    webResources: {
        images: false, // Disable images inlining
        relativeTo: "./path_to_your_css/"
    }
}, callback);

Juice uses web-resources-inliner, and by default it will try to inline everything, even images and fonts, creating an error every time it tries to fetch these, because they usually never are in the same folder as the script running Juice.

More details in the Juice documentation : https://github.com/Automattic/juice#options

web-resource-inliner's Options object : https://github.com/jrit/web-resource-inliner#options