webpack-contrib/mini-css-extract-plugin

When using a forward-slash in `filename`, the wrong font url is generated

Devqon opened this issue · 6 comments

Bug report

When prefixing the filename using a forward-slash the wrong url path is generated in the css when referencing fonts (and probably other asset types).

I have the following directory structure:
image

With this webpack (5!) configuration:

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

module.exports = {
    entry: './src/main.scss',
    output: {
        path: path.resolve(__dirname, 'dist'),
        clean: true,
    },
    plugins: [
        new webpack.ProgressPlugin(),
        new MiniCssExtractPlugin({
            filename: `/styles/[name].css`,
            ignoreOrder: false,
        }),
    ],
    module: {
        rules: [
            {
                test: /\.js$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: ['@babel/preset-env']
                }
            },
            {
                test: /\.scss$/,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
                include: path.resolve(__dirname, './src'),
            },
            {
                test: /\.(eot|otf|webp|svg|ttf|woff|woff2)$/,
                exclude: [/images/, /icons/],
                type: 'asset/resource',
                generator: {
                  filename: `fonts/[name][ext]`,
                }
            }
        ]
    },
    devtool: 'source-map',
}

This generates a font path in my (generated) css (from scss):
image

When removing the prefixed forward-slash in filename, the following output is generated:
image

Actual Behavior

The generated font urls contains a double directory upward crawl (../../fonts/my-font)

Expected Behavior

The generated font url should contains a single directory upward (../fonts/my-font)

How Do We Reproduce?

See above given webpack configuration and directory structure, or this zip contains the source:
mini-css-extract-plugin-bug-report.zip

Output of npx webpack-cli info:

  Browsers:
    Edge: Spartan (44.22000.120.0), Chromium (96.0.1054.34)
    Internet Explorer: 11.0.22000.120
  Packages:
    babel-loader: ^8.2.3 => 8.2.3
    css-loader: ^6.5.1 => 6.5.1
    html-webpack-plugin: ^5.5.0 => 5.5.0
    sass-loader: ^12.3.0 => 12.3.0
    style-loader: ^3.3.1 => 3.3.1
    webpack: ^5.64.4 => 5.64.4
    webpack-cli: ^4.9.1 => 4.9.1

Do not use / at the start of filename, it is invalid

Because filename is absolute path in this case, so URLs are wrong, we should improve schema

If it is invalid, it should throw a build error in my opinion. I've waisted hours to find why webpack was generating the wrong paths in our complicated build setup, and I would like to prevent others wasting their time on sthis :)

You can send a PR and help us, thanks!