背景
按照 Ant Design 官網用 React 腳手構建的後臺項目,剛接手項目的時候大概30條路由左右,我的用的機子是 Mac 8G 內存,打包完成需要耗時2分鐘左右,決定優化一下。
項目技術棧: React + React Router + TypeScript + Ant Design
構建時間慢可能的原因:
-
React 腳手架默認打包構建出來的文件包含 map 文件
-
Ant Desigin 以及項目中使用的第三方模塊太大
-
babel-loader 編譯過程慢
React 腳手架修改 Webpack 配置方案:
-
npm run rject 暴露出 Webpack 配置信息,直接進行修改。
-
使用 react-app-rewired (一個對 create-react-app 進行自定義配置的社區解決方案)Ant Design 官網推薦。
自定義Webpack
配置步驟:
-
基礎配置
-
開發環境配置
-
生產環境配置
使用 customize-cra 修改React 腳手架配置實踐
1、準備工作
npm i react-app-rewired customize-cra --save-dev 安裝 react-app-rewired
,customize-cra
,它提供一些修改 React 腳手架默認配置函數,具體參見:https://github.com/arackaf/customize-cra
安裝後,修改 package.json
文件的 scripts
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
}
項目根目錄創建一個 config-overrides.js
用於修改Webpack
配置。
Ant Desigin
提供了一個按需加載的 babel 插件 babel-plugin-import
antd-dayjs-webpack-plugin
是Ant Desigin
官方推薦的插件,用於替換moment.js
安裝 npm i babel-plugin-import --save-dev
,並修改config-overrides.js
配置文件
override
函數用來覆蓋React
腳手架Webpack
配置;fixBabelImports
修改babel
配置
const { override, fixBabelImports,addWebpackPlugin } = require('customize-cra');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
module.exports = override(
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
addWebpackPlugin(new AntdDayjsWebpackPlugin())
);
以上是Ant Desigin
推薦的做法。
2、首屏加載優化
npm i react-loadable customize-cra --save
安裝react-loadable
模塊,然後在路由文件裏使用如下,loading
組件可以自定義。這樣打包的時候會爲每個路由生成一個chunk
,以此來實現組件的動態加載。
需要安裝"@babel/plugin-syntax-dynamic-import
這個插件,編譯import()
這種語法
import Loadable from 'react-loadable';
const Index = Loadable({
loader:() => import('../components/Index'),
loading:SpinLoading
});
3、去掉 map 文件
首先安裝依賴包webpack-stats-plugin
webpack-bundle-analyzer
前者爲了統計打包時間會在打包後的文件夾裏生成一個stats.json
文件,後者用來分析打包後的各個模塊的大小。
process.env.GENERATE_SOURCEMAP = "false";
用來去掉打包後的map
文件
const { override, fixBabelImports } = require('customize-cra');
const { StatsWriterPlugin } = require("webpack-stats-plugin");
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
let startTime = Date.now()
if(process.env.NODE_ENV === 'production') process.env.GENERATE_SOURCEMAP = "false"
// 自定義生產環境配置
const productionConfig = (config) =>{
if(config.mode === 'production'){
config.plugins.push(...[
new StatsWriterPlugin({
fields: null,
transform: (data) => {
let endTime = Date.now()
data = {
Time: (endTime - startTime)/1000 + 's'
}
return JSON.stringify(data, null, 2);
}
}),
new BundleAnalyzerPlugin()
])
}
return config
}
module.exports = override(
productionConfig,
fixBabelImports('import', {
libraryName: 'antd',
libraryDirectory: 'es',
style: 'css',
}),
addWebpackPlugin(new AntdDayjsWebpackPlugin())
);
去掉map
文件的打包時間,大約60s左右。查看打包後生成的分析圖發現Ant Desigin
的一些組件被重複打包,打包出來一共有13M多。
4、更細化分包
在productionConfig
配置添加,在入口文件添加vendors
用來分離穩定不變的模塊;common
用來抽離複用模塊;styles
將css
文件抽離成一個文件;
// 針對生產環境修改配置
const productionConfig = (config) =>{
if(config.mode === 'production'){
const splitChunksConfig = config.optimization.splitChunks;
if (config.entry && config.entry instanceof Array) {
config.entry = {
main: config.entry,
vendors: ["react", "react-dom", "react-router-dom", "react-router"]
}
} else if (config.entry && typeof config.entry === 'object') {
config.entry.vendors = ["react", "react-loadable","react-dom", "react-router-dom","react-router"];
}
Object.assign(splitChunksConfig, {
cacheGroups: {
vendors: {
test: "vendors",
name: 'vendors',
priority:10,
},
common: {
name: 'common',
minChunks: 2,
minSize: 30000,
chunks: 'all'
},
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
priority: 9,
enforce: true
}
}
})
config.plugins.push(...[
new StatsWriterPlugin({
fields: null,
transform: (data) => {
let endTime = Date.now()
data = {
Time: (endTime - startTime)/1000 + 's'
}
return JSON.stringify(data, null, 2);
}
}),
new BundleAnalyzerPlugin()
])
}
return config
}
以上實際打包運行大約35S左右,實際打包後的模塊一共2.41M,打包後生成的分析圖發現Ant Design
有個圖標庫特別大,大約有520kb,但是實際項目中用到的圖標特別少。到此不想繼續折騰React
腳手架了,還不如重新配置一套Webpack
替換腳手架。
5、總結
-
React
腳手架配置過重,對於龐大的後臺系統不實用 -
Ant Design
的圖標庫沒有按需加載的功能 -
修改
React
腳手架配置太麻煩
Webpack
配置實踐
1、結果:替換掉腳手架後,陸陸續續新增路由到100條左右,打包耗時大概20s-30S之間,業務代碼打包後1.49M,可以接受。
2、優化點:
-
利用
autodll-webpack-plugin
插件,生產環境通過預編譯的手段將Ant
React
等穩定的模塊全部先抽離出來,只打包編譯業務代碼。 -
babel-loader
開啓緩存 -
利用
happypack
加快編譯速度 -
生產環境不開啓
devtool
-
細化分包
-
針對項目輕量級配置(後臺項目,基本只在 Chrome 瀏覽器下使用)
問題:
-
抽離出來的第三方模塊大概有3M多,經過
zip
大概也有800多Kb
,首屏加載比較慢。如果結合externals
屬性將這些靜態資源放置到CDN
上或許加載會更快。
3、基礎配置:
放於webpack.base.config.js
文件
1、安裝babel
模塊,使用的是babel7.0
版本。
npm i install babel-loader @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript @babel/plugin-transform-runtime --save-dev
npm i @babel/runtime-corejs3 --save
在更目錄下創建babel.config.js
babel
的配置文件
module.exports = function (api) {
api.cache(true);
const presets = ["@babel/env","@babel/preset-react","@babel/preset-typescript"];
const plugins = [
["@babel/plugin-transform-runtime", {
corejs: 3,
}],
"@babel/plugin-syntax-dynamic-import",
"@babel/plugin-proposal-class-properties",
];
if (process.env.NODE_ENVN !== "production") {
plugins.push(["import", {
"libraryName": "antd", // 引入庫名稱
"libraryDirectory": "es", // 來源,default: lib
"style": "css" // 全部,or 按需'css'
}]);
}
return {
presets,
plugins
};
}
2、babel-loader
配置:
const os = require('os');
const HappyPack = require('happypack');
const happyThreadPool = HappyPack.ThreadPool({ size: os.cpus().length });
module.exports = {
.....
module: {
rules: [
{
test: /\.(ts|tsx|js|jsx)$/,
exclude: /node_modules/,
loaders: ['happypack/loader?id=babel']
}
},
plugins: [
new HappyPack({
id: 'babel',
threadPool: happyThreadPool,
loaders: [{
loader:'babel-loader',
options: {
cacheDirectory: true
}
}]
})
]
}
3、mini-css-extract-plugin
插件打包抽離CSS到單獨的文件
var MiniCssExtractPlugin = require('mini-css-extract-plugin');
var NODE_ENV = process.env.NODE_ENV
var devMode = NODE_ENV !== 'production';
var utils = require('./utils')
module.exports = {
....
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
options: {
// only enable hot in development
hmr: devMode,
// if hmr does not work, this is a forceful method.
reloadAll: true,
},
},
"css-loader"
],
},
]
},
plugins: [
new MiniCssExtractPlugin({
//utils.assetsPath 打包後存放的地址
filename: devMode ? '[name].css' : utils.assetsPath('css/[name].[chunkhash].css'),
chunkFilename: devMode ? '[name].css' : utils.assetsPath('css/[name].[chunkhash].css'),
ignoreOrder: false, // Enable to remove warnings about conflicting order
})
]
}
4、html-webpack-plugin
生成html
文件
const HtmlWebpackPlugin = require('html-webpack-plugin')
var htmlTplPath = path.join(__dirname, '../public/')
module.exports = {
....
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
template: htmlTplPath + 'index.html',
inject: true,
})
]
}
5、webpack.DefinePlugin
生成業務代碼可以獲取的變量,可以區分環境
const webpack = require('webpack')
module.exports = {
....
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(devMode ? 'development' : 'production'),
'perfixerURL': JSON.stringify('//yzadmin.111.com.cn')
}),
}
4、開發環境配置:
放於webpack.development.config.js
文件
var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
var entryScriptPath = path.join(__dirname, '../src/')
var base = require('./webpack.base.config');
module.exports = merge(base, {
entry: {
app: [entryScriptPath+'index'] // Your appʼs entry point
},
output: {
path: path.join(__dirname, '../dist/'),
filename: '[name].js',
chunkFilename: '[name].[chunkhash].js'
},
module: {
},
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /zh-cn/),
new webpack.HotModuleReplacementPlugin(),
new FriendlyErrorsPlugin(),
]
});
start.js
文件,用於npm start
啓動本地服務
var webpack = require('webpack');
var opn = require('opn')
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.development.config');
config.entry.app.unshift("webpack-dev-server/client?http://127.0.0.1:9000/", "webpack/hot/dev-server");
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: {
index: '/public'
}
}).listen(9000, '127.0.0.1', function (err, result) {
if (err) {
return console.log(err);
}
opn('http://127.0.0.1:9000/')
});
5、生產環境配置:
放於webpack.production.config.js
文件
const path = require('path')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.config');
const config = require('./webpack.env.config')
const utils = require('./utils')
const AutoDllPlugin = require('autodll-webpack-plugin');
const TerserJSPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
const webpackConfig = merge(baseWebpackConfig, {
module: {
},
devtool: config.build.productionSourceMap ? '#source-map' : false,
entry: {
app: resolve('src/index'),
},
output: {
path: config.build.assetsRoot,
filename: utils.assetsPath('js/[name].[chunkhash].js'),
chunkFilename: utils.assetsPath('js/[name].[chunkhash].js')
},
optimization: {
minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
splitChunks: {
cacheGroups: {
common: {
test: /[\\/]src[\\/]/,
name: 'common',
chunks: 'all',
priority: 2,
minChunks: 2,
},
// 分離css到一個css文件
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
priority: 9,
enforce: true,
}
}
},
runtimeChunk: {
name:"manifest"
}
},
plugins: [
new AutoDllPlugin({
inject: true, // will inject the DLL bundles to index.html
filename: '[name].dll.js',
path: './dll',
entry: {
// 第三方庫
react: ["react","react-dom","react-router", "react-router-dom",'react-loadable'],
antd: ['antd/es'],
untils: ['qs','qrcode'],
plugins:['braft-editor','js-export-excel']
}
})
]
})
if (config.build.productionGzip) {
const CompressionWebpackPlugin = require('compression-webpack-plugin')
webpackConfig.plugins.push(
new CompressionWebpackPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(' +
config.build.productionGzipExtensions.join('|') +
')$'
),
threshold: 10240,
minRatio: 0.8
})
)
}
if (config.build.bundleAnalyzerReport) {
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
}
module.exports = webpackConfig
build.js
用於npm run build
構建
process.env.NODE_ENV = 'production'
var ora = require('ora')
var path = require('path')
var chalk = require('chalk')
var shell = require('shelljs')
var webpack = require('webpack')
var config = require('./webpack.env.config')
var webpackConfig = require('./webpack.production.config')
var spinner = ora('building for production...')
spinner.start()
var assetsPath = path.join(config.build.assetsRoot, config.build.assetsSubDirectory)
shell.config.silent = true
shell.rm('-rf', assetsPath)
shell.mkdir('-p', assetsPath)
shell.cp('-R', 'static/*', assetsPath)
shell.config.silent = false
webpack(webpackConfig, function (err, stats) {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false,
chunks: false,
chunkModules: false
}) + '\n\n')
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
修改package.json
"scripts": {
"start": "node webpack/start.js",
"build": "node webpack/build.js"
},
6、總結
-
通過本次實踐大致對
Webpack
有了初步瞭解,但關於Webpack
的內部原理沒有仔細探究過 -
對一些腳手架做配置修改的前提是需要了解
Webpack
基礎內容 -
優化一個項目首先需要知道是大致什麼原因造成的,可以利用的工具有
speed-measure-webpack-plugin
,webpack-bundle-analyzer
等 -
項目雖然加入了
typeScript
但並沒有很好的利用typeScript
最後
Webpack
配置demo
地址:https://github.com/ccokl/webpack/tree/master/_webpack_for_ant