mini-css-extract-plugin
mini-css-extract-plugin 插件会将 CSS 提取到单独的文件中,为每个包含 CSS 的 JS 文件创建一个 CSS 文件,并且支持 CSS 和 SourceMaps 的按需加载。
准备
-
安装
mini-css-extract-plugin
依赖yarn add mini-css-extract-plugin -D
语法
-
webpack.config.js
配置webpack.module
,将style-loader
替换为miniCssExtractPlugin.loader
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"],
},
{
test: /\.less$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"less-loader",
],
},
{
test: /\.s(c|a)ss$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
} -
webpack.config.js
配置webpack.plugins
, 用于配置抽离的css
文件形式new MiniCssExtractPlugin({
filename: 'css/[name].css', // 或者 filename: '[name].css'
}) -
webpack.config.js
完整配置如下:const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
exclude: /node_modules/,
use: [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader"],
},
{
test: /\.less$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"less-loader",
],
},
{
test: /\.s(c|a)ss$/,
exclude: /node_modules/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name].css',
}),
],
};