Now I read the config that package the scss file write like this:
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test : /\.(scss)$/ ,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true,
sourceMap: true
}
},
"sass-loader"
]
}
why the scss file need 3 type of loader? what is the parse process? first using MiniCssExtractPlugin.loader then css-loader and finnally sass-loader? why did not using the only one sass-loader to parse the scss file?
CodePudding user response:
Each loader do only one simple work:
- the
sass-loadercompile the Sass to pure CSS string. But can't save it into a CSS file. - the
css-loader"catch" the compiled CSS string and export as JS module to handle it in additional loaders. The loader can't save a CSS file. - the
MiniCssExtractPlugin.loaderis a middleware for own plugin. It do not others as "catch" JS module fromcss-loaderand pass it into pluginMiniCssExtractPlugin. - The plugin
MiniCssExtractPluginextract the pure CSS string and save it as CSS file.
NOTE: Webpack generate a js file for each resource defined in webpack entry.
Themini-css-extract-pluginextract css, but not eliminate a generated empty js file.
To remove unexpected empty js file use the plugin webpack-remove-empty-scripts.
The minimal webpack.config.js to extract css from scss.
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
module.exports = {
entry: {
'styles': './assets/scss/styles.scss',
},
module: {
rules: [
{
test: /\.(scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {
modules: true,
sourceMap: true
}
},
'sass-loader',
]
},
]
},
plugins: [
new RemoveEmptyScriptsPlugin(), // <== remove empty js files
new MiniCssExtractPlugin({
filename: '[name].[chunkhash:8].css', // <== save CSS file
}),
],
};
``
