切换生产模式和开发模式
创建webpack.config.prod.js文件和webpack.config.base.js文件。将公共配置放在webpack.config.base.js文件中,将开发模式配置放在webpack.config.js中,将生产模式放在webpack.config.prod.js中(代码如下)。在package.json的build中添加 --config webpack.config.prod.js
当运行在命令行运行 yarn start
时为开发模式;当在命令行运行 yarn build
为生产模式。
webpack.config.js文件
const path = require('path');
const base = require('./webpack.config.base.js')
module.exports = {
...base,
mode: 'development',
devtool: 'inline-source-map',
devServer: {
contentBase: './dist',
},
optimization: {
runtimeChunk: 'single',
},
module: {
rules: [
...base.module.rules,
{
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
],
},
};
webpack.config.prod.js文件
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const base = require('./webpack.config.base.js')
module.exports = {
...base,
mode: 'production',
plugins: [
...base.plugins,
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css',
chunkFilename: '[id].[contenthash].css',
ignoreOrder: false,
}),
],
module: {
rules: [
...base.module.rules,
{
test: /\.css$/i,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: "/public/path/to/",
},
},
"css-loader",
],
},
],
},
optimization: {
runtimeChunk: 'single',
},
};
webpack.config.base.js文件
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: '[name].[contenthash].js',
},
plugins: [
new HtmlWebpackPlugin({
title: 'My App',
template: 'src/assets/index.html'
}),
],
module: {
rules: [
{
test: /\.less$/i,
use: [
// compiles Less to CSS
'style-loader',
'css-loader',
'less-loader',
],
},
{
test: /\.s[ac]ss$/i,
use: [
// 将 JS 字符串生成为 style 节点
'style-loader',
// 将 CSS 转化成 CommonJS 模块
'css-loader',
// 将 Sass 编译成 CSS
'sass-loader',
],
},
{
test: /\.styl$/,
loader: ['style-loader','css-loader','stylus-loader'] // 将 Stylus 文件编译为 CSS
},
{
test: /\.(png|jpg|gif)$/i,
use: ['file-loader'],
},
],
},
};
package.json
{
"name": "webpack-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack serve",
"build": "rm -rf dist && webpack --config webpack.config.prod.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@webpack-cli/serve": "^1.7.0",
"css-loader": "^3.2.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^3.2.0",
"less": "^4.1.3",
"less-loader": "5.0.0",
"mini-css-extract-plugin": "1.6.2",
"sass": "^1.54.9",
"sass-loader": "^10",
"style-loader": "^1.0.1",
"stylus": "^0.59.0",
"stylus-loader": "3.0.2",
"webpack": "^4.41.2",
"webpack-dev-server": "^3.9.0"
},
"dependencies": {
"webpack-cli": "^4.10.0"
}
}