当使用MiniCssExtractPlugin
生成的css在dist下一个文件夹时(如dist/css/style.css
),此时如果不设置生成的css的公共路径(publicPath
),图片不会正常显示。
因为css-loader
以为生成的style.css
文件直接在dist目录下,所以图片路径会默认设置为url(./随机名字.png)
,而事实上图片的正确的路径为url(../随机名字.png)
。
img-demo|- package.json|- webpack.config.js|- /dist|- index.js|- index.html+ |- 随机字符.png+ |- /css+ |- style.css|- /src|- icon.png|- style.css|- index.js|- /node_modules
因此,需要在options
中设置publicPath
为../
,这样该css文件引入的所有url前面都会加上../
的前缀。
webpack.config.js
const path = require('path');const MiniCssExtractPlugin=require('mini-css-extract-plugin');module.exports = {entry: {index: './src/index.js',},output: {filename: '[name].js',path: path.resolve(__dirname, 'dist'),},module:{rules:[{test:/\.css$/i,//此时生成的css在dist/css的文件夹下,要设置公共路径//这样该css文件所有的url前面都会加上../的前缀。+use:[{+loader:MiniCssExtractPlugin.loader,+options:{+ publicPath:'../'+}+}, 'css-loader']},{test:/\.(png|svg|jepg|gif)/,type:'asset/resource'}] },plugins: [+ new MiniCssExtractPlugin({+ //在dist/css文件夹下创建一个index.css文件+ filename:'css/[name].css'+ })],mode: 'development'};
ps:如果想要复制上面的代码,请去掉+号。+号仅用来突出显示需要添加的代码。
使用mini-css-extract-plugin插件CSS的路径问题 图片不显示的解决办法为设置公共路径 | webpack plugin