Resolve url() to image without bundling

580 Views Asked by At

I'm integrating Webpack into an already established front-end environment. Sass and resolve-url-loader are working and Webpack finds the files that are referenced by the url() in the CSS. My problem is, I don't want to copy the files referenced by url() into the dist/ folder, I want to link to them where they are.

My files are setup like this

www/
  index.html
  assets/
    js/
      main.js
    css/
      main.scss
      components/
        thing.scss
    images/
      pic.jpg
  dist/
    output.js
    output.css

with main.scss importing thing.scss which contains the line

background: url(../../images/pic.jpg)

resolve-url-loader correctly resolves this to be ../images/pic.jpg and css-loader finds the file and the loader for the file (file-loader) is called. However, I would like to not copy the file into dist/ (which I did by adding emitFile: false to file-loader) and to rewrite the url to be relative from the CSS output (../assets/images/pic.jpg). How do I do this?

For reference, here is my webpack.config.js

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

{
    entry: './assets/js/main.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'output.js',
        publicPath: 'dist/'
    },
    module: {
        rules: [{
            test: /\.scss$/,
            use: [
                MiniCssExtractPlugin.loader, {
                    loader: "css-loader",
                    options: {
                        sourceMap: true,
                        url: false
                    }
                }, {
                    loader: "resolve-url-loader",
                    options: {
                        debug: true,
                        sourceMap: true
                    }

                }, {
                    loader: "sass-loader",
                    options: {
                        sourceMap: true,
                        sourceMapContents: false
                    }
                }
            ]
        }, {
            test: /\.(png|svg|jpg|gif)$/,
            use: [{
                loader: 'file-loader',
                options: {
                    emitFile: false
                }
            }]
        }]
    },
    plugins: [new MiniCssExtractPlugin({
        filename: "[name].css",
        chunkFilename: "[id].css"
    })],

}

1

There are 1 best solutions below

0
On

Not the best answer but it works.

Remove resolve-url-loader and keep css-loader on url:false. Then just write your URL paths as they would work from the output file.

I'll probably accept it and bundle my images though.