Skip to content

Asset links broken when extracting CSS and assets to different folders #691

@fenomas

Description

@fenomas
  • Operating System: OSX
  • Node Version: v14.15.4
  • NPM Version: 6.14.10
  • webpack Version: 5.15.0
  • mini-css-extract-plugin Version: ^1.3.5

Expected Behavior

I'm using MiniCssExtractPlugin to extract CSS, and with default settings everything works fine. However I want to export the CSS to its own folder, separate from image assets, like this:

build/styles/bundle.css
build/assets/image.png

Per the docs, I'm doing this by passing a filename option to the plugin with the desired folder name.

Actual Behavior

When I pass in an option like: filename: 'styles/[name].css, the CSS file itself gets exported to the correct directory. However, url(..) asset links inside the CSS aren't adjusted, and wind up broken as a result.

Specifically, styles/bundle.css winds up containing references like url(assets/image.png), causing the browser to request styles/assets/image.png.

Code

The relevant code snippets look like this:

/* webpack.config.js */
    output: {
        filename: 'js/[name].[contenthash:8].js',
        path: path.resolve('.', 'build'),
        publicPath: '',
    },
    plugins: [
        new VueLoaderPlugin(),
        new HtmlWebpackPlugin({ /* .. */ }),
        new MiniCssExtractPlugin({
            filename: 'styles/[name].css' }
        ),
    ],
    module: {
        rules: [
            // ...
            {
                test: /\.png$/,
                type: 'asset/resource',
                generator: { filename: 'assets/[name][ext]' },
            },
            {
                test: /\.css$/,
                use: [ MiniCssExtractPlugin.loader, 'css-loader' ],
            },
/* /src/foo/bar.css */
.whatever {
    background-image: url('~path/to/image.png');
}

After running webpack, the CSS winds up with broken asset links:

/* styles/bundle.css */
.whatever {
    background-image: url('assets/image.png');
        /* should be: url('../assets/image.png') or similar */
}

How Do We Reproduce?

By building a project with configuration as described above (in production mode).


Is there some setting or workaround supporting this use case?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions