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???
This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.
ExtractTextPlugin. extract(options: loader | object) Creates an extracting loader from an existing loader. Supports loaders of type { loader: [name]-loader -> {String}, options: {} -> {Object} } .
css-loader is the npm module that would help webpack to collect CSS from all the css files referenced in your application and put it into a string. And then style-loader would take the output string generated by the above css-loader and put it inside the <style> tags in the index. html file.
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,
}),
]
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With