本文内容如下
性能优化相关内容
如果你都有了答案,可以忽略本文章,或去webpack学习导图寻找更多答案
区分模式打包
根据开发环境或生产环境而使用不同的配置,因为有些配置是开发模式使用,有些是生产环境使用
如何区分
把配置分为3个文件,根据环境变量来结合:
webpack.common.js(公共配置)
- 入口文件
- 出口文件
- module…
webpack.dev.js(开发配置)
- devServe
- eslint
- source-map…
webpack.pro.js(生产配置)
- externals忽略打包
- 代码压缩…
重点:通过执行命令来区分环境变量
build是生产环境配置:加上 --env production,用于区分环境
"scripts": {
"start": "webpack-dev-server --config ./build/webpack.common.js",
"dev": "webpack --config ./build/webpack.common.js",
"build": "webpack --env production --config ./build/webpack.common.js",
},
注意: 这里都是执行webpack.common.js,通过 webpack-merge 这个包来根据环境 合并配置
webpack.common.js
const { merge } = require('webpack-merge')
const devConfig = require('./webpack.dev.js')
const prodConfig = require('./webpack.pro.js')
const commonConfig = {...} //公共配置
读取env环境变量
module.exports = (env) => {
if (env && env.production) {
console.log('pro');
return merge(commonConfig, prodConfig)
} else {
console.log('dev');
return merge(commonConfig, devConfig)
}
}
结果:
如果执行yarn dev, 是development环境: commonConfig + devConfig
如果执行yarn build, 是production环境: commonConfig + prodConfig
例子
webpack.common.js
const { resolve } = require('path');
const { DefinePlugin } = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { merge } = require('webpack-merge')
const devConfig = require('./webpack.dev.js')
const prodConfig = require('./webpack.pro.js')
const commonConfig = {
entry: {
main: './src/index.js',
},
output: {
path: resolve(__dirname, '../dist'),
filename: 'js/[name].[contenthash:8].js',
},
resolve: {
extensions: ['.js', '.jsx', '.json', '.css', '.less', '.ts', '.tsx'],
},
module: {
rules: [
{
oneOf: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true //css模块化
}
},
{
loader: 'postcss-loader',
options: {
postcssOptions: { plugins: ['postcss-preset-env'] },
},
}],
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: { plugins: ['postcss-preset-env'] },
},
},
'less-loader'],
},
{
test: /\.(jpg|png|gif|jpe?g)$/,
type: 'asset',
generator: {
filename: 'img/[name].[contenthash:4][ext]',
},
parser: {
dataUrlCondition: {
maxSize: 8 * 1024,
},
},
},
{
test: /\.svg$/,
type: 'asset/inline',
},
{
test: /\.(t|j)sx?$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader',
options: {
cacheDirectory: true //开启babel缓存
}
}]
},
]
}
],
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: 'public/index.html', // 指定html模板,以该模板注入打包模块
title: '代码研习', // 修改html标题,需要配置模板语法<title><%= htmlWebpackPlugin.options.title %></title>
minify: { // html代码压缩
collapseWhitespace: true, // 移除空格
removeComments: true, // 移除注释
},
}),
new MiniCssExtractPlugin({
filename: 'css/[name]-[contenthash:8].css',
}),
new DefinePlugin({
PUBLIC_URL: '"./"',
}),
new CopyWebpackPlugin({
patterns: [
{
from: 'public', // 不用写to,会根据output自动设置
globOptions: {
ignore: ['**/index.html'],
},
},
],
}),
],
}
//根据配置package.json -> scripts 的环境变量来执行文件,如果没有配置,就走开发模式
module.exports = (env) => {
if (env && env.production) {
console.log('pro');
return merge(commonConfig, prodConfig)
} else {
console.log('dev');
return merge(commonConfig, devConfig)
}
}
webpack.dev.js
const ESLintPlugin = require('eslint-webpack-plugin');
const ReactRefresh = require('@pmmmwh/react-refresh-webpack-plugin');
const devConfig = {
mode: 'development',
devtool: 'cheap-module-source-map',
target: 'web',
devServer: {
port: '3000', // 端口号
open: true, // 启动之后自动打开浏览器
compress: true, // 启动gzip压缩,减少代码
hot: true, // 开启热更新,一般只会更新css,需要手动刷新
historyApiFallback: true,
proxy: { // 设置服务器代理,解决跨域问题
'/api': {
target: 'https://api.github.com',
pathRewrite: {
'^/api': '',
},
changeOrigin: true
},
},
},
plugins: [
new ESLintPlugin({
fix: true,
extensions: ['js', 'jsx', 'json', 'ts', 'tsx'],
exclude: '/node_modules/',
}),
new ReactRefresh(), //React HMR模块更新
]
};
module.exports = devConfig
webpack.pro.js
const { resolve } = require('path')
const Webpack = require('webpack')
const CssMinimizer = require('css-minimizer-webpack-plugin');
const AddAssetHtml = require('add-asset-html-webpack-plugin')
const proConfig = {
mode: 'production',
plugins: [
new CssMinimizer(),
new Webpack.DllReferencePlugin({
manifest: resolve(__dirname, '../dll/manifest.json')
}),
new AddAssetHtml({
filepath: resolve(__dirname, '../dll/vendor.dll.js')
})
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
}
},
externals: {}
};
module.exports = proConfig
总结:
学习更多