webpackwebpack-file-loaderwebpack-5

Webpack file-loader adjust public path


I have the following for my images folder:

module.exports = {
        test: /\.(png|jpe?g|gif|svg)$/,
        include: config.paths.images, // this is: path.resolve(__dirname, '../assets/images')
        loader: 'file-loader',
        options: {
            name: '[path][name].[ext]',
            publicPath: '../',
        }
    };

And this is what outputs for my css: background-image: url(../images/assets/images/doctor-results/g-map-location.png);

What I need is for the path to be: background-image: url(../images/doctor-results/g-map-location.png);

Essentially removing the first 2 directories from the path, while remaining relative.


Solution

  • I ended up using split and splice instead of adding another library.

    {    
        options: {
            name: config.outputs.image.filename,
            publicPath: (url) => {
                const pathArray = url.split('/');
                pathArray.splice(0, 2);
                const path = pathArray.join('/');
                return `../${path}`;
            },
            emitFile: false
        }
    }