參考官方文檔:https://webpack.docschina.org/plugins/mini-css-extract-plugin/
webpack5以上可用过吻,用mini-css-extract-plugin 插件蔗衡,支持js和css打包分離。
webpack.pro.config.js 中新增如下:
const path = require('path');
const { merge } = require('webpack-merge');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
-------------------------------------------------------
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
-------------------------------------------------------
const webpackConfigBase = require('./webpack.base.config');
const webpackConfigProd = {
mode: 'production',
plugins: [
new CleanWebpackPlugin({
protectWebpackAssets: true,
}),
-------------------------------------------------------
new MiniCssExtractPlugin({
filename: '[name].[fullhase:4].css',
}),
-------------------------------------------------------
new HtmlWebpackPlugin({
inject: 'body',
title: 'React APP',
filename: 'index.html',
template: path.join(__dirname, '../src/index.html'),
}),
],
};
module.exports = merge(webpackConfigBase, webpackConfigProd);
webpack.base.config.js 中
module: {
rules: [
{
test: /\.js[x]/,
use: 'babel-loader',
},
{
test: /\.ts[x]/,
use: 'ts-loader',
},
{
test: /\.(sc|c)ss/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
],
},
根據(jù)情況使用不同的loader插件
最后package.json 中增加如下:
"scripts": {
"dev": "webpack server --progress --config config/webpack.dev.config.js",
"build": "NODE_ENV=production webpack --progress --config config/webpack.prod.config.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
這樣济蝉,build完之后,js和css將分離贺嫂。