Css-loader: __webpack_public_path__ and url()

Created on 30 Sep 2015  路  5Comments  路  Source: webpack-contrib/css-loader

Normally, when you have assets in CSS that reference absolute or relative paths (e.g., content: url(/images/logo.svg)), the asset is resolved from the same host as the CSS file.

When using webpack, if you set output.publicPath to a relative path, CSS that gets injected into the page with JavaScript uses the host for the current document to resolve these paths.

If you host your static assets on a CDN, you can add a prefix to output.publicPath so that the assets resolve from the CDN's host. This transformation is applied during build-time. However, if you use __webpack_public_path__ to provide a public path to a CDN during run-time, the relative paths in CSS will unexpectedly resolve from the host of the current document.

Is this something that can be fixed?

I've looked at using ExtractTextPlugin to workaround this issue (since a CSS file on the CDN will cause the paths to resolve to the CDN), but I'd still prefer to have the CSS injected into the page through JavaScript.

Also, it seems like not using __webpack_public_path__ would be the easiest solution. However, there are some technical reasons why we want to provide a CDN at run-time rather than at build-time (load balancing issues, being able to change CDN configuration without re-building, etc).

Any suggestions on what else can be done?

Most helpful comment

Same issue here; any support for __webpack_public_path__ in extract-text-webpack-plugin ??

All 5 comments

To use a runtime public path:

  • You must not use the extract-text-webpack-plugin.
  • You must set __webpack_public_path__ before referencing the stylesheets or images. (ES6 imports is moved to the top, be careful. Best use a extra file for setting the runtime path)

Just wondering if there is a solution to this that allows using __webpack_public_path__ with the extract-text-webpack-plugin now.

Same issue here; any support for __webpack_public_path__ in extract-text-webpack-plugin ??

Practically it doesn't seem possible with external css files. In javascript, the compiled code gets something like

module.exports = __webpack_require__.p + "images/my-img.svg";

But in css file, this is obviously not possible. :(

Although, I'd love to hear if there's anything we can do to support this feature.

For anyone coming through this old issue, here's a relevant PR in file-loader that might help things: https://github.com/webpack-contrib/file-loader/pull/334

Was this page helpful?
0 / 5 - 0 ratings