Webpack url-loader dynamic public path

4.1k Views Asked by At

I'm using webpack's url-loader plugin and have it configured like this:

module.exports = {
    entry: './src/admin.planningview.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: 'http://poc.local/dist/'
    },
    module: {
        rules: [
            {
                test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                loader: 'url-loader?limit=100000'
            }
        ]
    }
};

Inside my base.css there is the following line:

@font-face {
    font-family: 'open_sansregular';
    src: url('fonts/opensans-regular-webfont.eot');
    src: url('fonts/opensans-regular-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/opensans-regular-webfont.woff') format('woff'), url('fonts/opensans-regular-webfont.ttf') format('truetype'), url('fonts/opensans-regular-webfont.svg#open_sansregular') format('svg');
    font-weight: normal;
    font-style: normal;
}

This files are located in the sub folder 'fonts'.

My dist folder looks like this: enter image description here

Now I'm trying to load all these files based on a dynamic publicPath variable (so overriding the http://poc.local/dist/ url) for the chunks and assets.

I added this is my entry point file:

__webpack_public_path__ = window.cdnURL;

The window.cdnURL contains something like : http://cdn.local/dist/

Now my problem is the chunks are being loaded properly but the fonts / woff files are not.. This seems to be something with the url-loader I think.

When I check the bundle.js in debug mode I see the following, it's the old URL:

enter image description here

Any idea's?

2

There are 2 best solutions below

2
On

Use the css-loader alias option: https://github.com/webpack-contrib/css-loader#alias

0
On

As far as my understanding goes, the file-loader (fallback for url-loader) will stringify the path at build time.

In order to use dynamic data, you need to use postTransformPublicPath:

module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/i,
        loader: 'file-loader',
        options: {
          publicPath: '/some/path/',
          // add the following. This could remove/replace "http://poc.local/dist/"
          // you would have to write JS code as a string.
          postTransformPublicPath: (p) => `__webpack_public_path__ + ${p}`,
        },
      },
    ],
  },
};