I am using MiniCssExtractPlugin to lazyload css files in my react application.
i have given publicPath option for MiniCssExtractPlugin but it is not taking this option value, it is taking output.publicPath option.
config:
{
test: /\.(css)?$/,
use: [{
loader : MiniCssExtractPlugin.loader,
options : {
publicPath : '../'
}
},
'css-loader'
],
}
Any help???
Seems as though your not the only one confused, 52 comments on how to get this right. The issue of publicPath in html-webpack-plugin was similar and helped. However, the biggest help was from npm run eject
ing out of the create-react-app and inspecting the webpack.config.js
files.
TL;DR: You need to specify the save path in the plugin constructor.
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
filename: "assets/css/[name].css",
}),
You might need to re-think the module output logic.
Avoid specifying a nested path in module.output.path
e.g. public/assets/js
, instead set the root directory: public
and set the nesting for the filename
key: assets/js/[name].js
.
You can then specify a publicPath
in the main module.output
that you would use for subdomains or CDN's etc.
The final complete config worked for me:
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const publicPath = '/';
module.exports = {
entry: './_src/_js/index.js',
output: {
filename: 'assets/js/[name].js',
path: path.resolve(__dirname, 'dist'),
publicPath: publicPath,
},
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
'css-loader',
],
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'assets/images/[name].[ext]',
},
},
]
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader','eslint-loader']
},
],
},
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: "assets/css/[name].css",
}),
new HtmlWebpackPlugin({
inject: true,
}),
]
};