Asset links broken when extracting CSS and assets to different folders
See original GitHub issue- 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!
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:46 (29 by maintainers)
@alexander-akait Take your time, there’s no rush. I’m already working around the issue myself; I only posted this issue for others who might encounter it.
@andyhall OK, please upgrade to 1.3.10 of @cactuslab/mini-css-extract-plugin. This now looks at the output filename template to work out any additional relative paths to consider. In your case, that is
styles/[name].css
so we get an extra../
which is what we need.In order to make it work with your repo I removed the
publicPath
line fromwebpack.config.js
(as"auto"
is the default), upgraded the plugin, and updated therequire
statement inwebpack.config.js
, then rannpm run build
.I am really straying into an area of interacting with the webpack API that I’m not at all familiar with. I hope there’s a function to render a filename template given a chunk… I’ve just regexed the name into the template in case the name contains path components!