背景

按照 Ant Design 官网用 React 脚手构建的后台项目,刚接手项目的时候大概30条路由左右,我的用的机子是 Mac 8G 内存,打包完成需要耗时2分钟左右,决定优化一下。

项目技术栈: React + React Router + TypeScript + Ant Design

构建时间慢可能的原因:

  1. React 脚手架默认打包构建出来的文件包含 map 文件

  2. Ant Desigin 以及项目中使用的第三方模块太大

  3. babel-loader 编译过程慢

React 脚手架修改 Webpack 配置方案:

  1. npm run rject 暴露出 Webpack 配置信息,直接进行修改。

  2. 使用 react-app-rewired (一个对 create-react-app 进行自定义配置的社区解决方案)Ant Design 官网推荐。

自定义Webpack配置步骤:

  1. 基础配置

  2. 开发环境配置

  3. 生产环境配置

使用 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-pluginAnt 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用来抽离复用模块;stylescss文件抽离成一个文件;

// 针对生产环境修改配置
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

基于 Ant Desigin 的后台管理项目打包优化实践的更多相关文章

  1. vue,vuex的后台管理项目架子structure-admin,后端服务nodejs

    之前写过一篇vue初始化项目,构建vuex的后台管理项目架子,这个structure-admin-web所拥有的功能 接下来,针对structure-admin-web的不足,进行了补充,开发了具有登 ...

  2. vue初始化项目,构建vuex的后台管理项目架子

    构架vuex的后台管理项目源码:https://github.com/saucxs/structure-admin-web 一.node安装 可以参考这篇文章http://www.mwcxs.top/ ...

  3. SSM 电影后台管理项目

    SSM 电影后台管理项目 概述 通过对数据库中一张表的CRUD,将相应的操作结果渲染到页面上. 笔者通过这篇博客还原了项目(当然有一些隐藏的坑),然后将该项目上传到了Github.Gitee,在末尾会 ...

  4. 【Vuejs】335-(超全) Vue 项目性能优化实践指南

    点击上方"前端自习课"关注,学习起来~ 前言 Vue 框架通过数据双向绑定和虚拟 DOM 技术,帮我们处理了前端开发中最脏最累的 DOM 操作部分, 我们不再需要去考虑如何操作 D ...

  5. 基于 Blazui 的 Blazor 后台管理模板 BlazAdmin 正式尝鲜

    简介 BlazAdmin 是一个基于Blazui的后台管理模板,无JS,无TS,非 Silverlight,非 WebForm,一个标签即可使用. 我将在下一篇文章讨论 Blazor 服务器端渲染与客 ...

  6. docloud后台管理项目(开篇)

    最近朋友做app需要web做后台管理,所以花了一周时间做了这个项目. 废话不多说,开发环境是nginx+php5.3,使用thinkphp框架.是一个医疗器械数据统计的后台,业务功能很简单就是查看用户 ...

  7. vue+webpack+element-ui项目打包优化速度与app.js、vendor.js打包后文件过大

    从开通博客到现在也没写什么东西,最近几天一直在研究vue+webpack+element-ui项目打包速度优化,想把这几天的成果记录下来,可能对前端牛人来说我这技术比较菜,但还是希望给有需要的朋友提供 ...

  8. 基于fastadmin快速搭建后台管理

    FastAdmin是一款基于ThinkPHP5+Bootstrap的极速后台开发框架:开发文档 下面对环境搭建简要概述,希望后来者能少走弯路: 1. 百度搜索最新版wampserver, 安装并启动 ...

  9. 【vue】MongoDB+Nodejs+express+Vue后台管理项目Demo

    ¶项目分析 一个完整的网站服务架构,包括:   1.web frame ---这里应用express框架   2.web server ---这里应用nodejs   3.Database ---这里 ...

随机推荐

  1. css常用样式对文本的处理演练

    CSS文本属性可定义文本的外观,这是毫无疑问的,其次css可以通过以下属性改变文字的排版,比方说letter-spacing实现字符间距text-indent: 2em;完成首行缩进2字符word-s ...

  2. VMvare桥接网络连接不上解决办法

    记一次学习中的突发状况.由于本人的pc时长要在不同的网络中进行切换,ip地址一般都是不固定的,所以我使用虚拟机的时候一般使用的都是让VMvare自动识别网络环境.直到今天遇到一种突发情况,VMvare ...

  3. linux命令——find

    简介:find是Linux系统中的常用命令(应用程序)之一.它是用来在指定目录层次结构(指定目录的子目录以及子目录的子目录)中查找符合指定条件的文件和目录 一:语法结构 find [directory ...

  4. 两分支部署Hexo

    最近把原本部署在GitHub上的hexo同时部署到码云上,速度快到飞起. 可做对比,我的GitHub Pages像乌龟一样慢吞吞,我的Gitee Pages像兔子一样敏捷. 使用hexo,如果换了电脑 ...

  5. 一些linux软件国内源

    1. ubuntu 版本号 Ubuntu 12.04 (LTS)代号为precise. Ubuntu 14.04 (LTS)代号为trusty. Ubuntu 15.04 代号为vivid. Ubun ...

  6. Jenkins+robotframework持续集成环境(二)

    配置Jenkins上的robotframework环境 一.添加robot插件 需要导一个robot framework 的包,导包方式如下: 1.进入插件管理页面,选择“可选插件”,在右侧搜索栏搜索 ...

  7. MATLAB代码v2.0

    % % V 原始评价指标矩 % % v_ij 第i个地区第j个指标的初始值 % % r_ij 第i个地区第j个指标的标准化值 % % R 标准化后的评价矩阵 % % m 统计地区总个数 % % n 已 ...

  8. 止损+TS

    单策略单品种单策略多品种多策略单品种和加仓多策略多品种静态仓位和动态仓位 金肯特钠(kingKeltner)布林强盗(BollingerBandit)动态突破(DynamicBreakOutII)恒温 ...

  9. 吴裕雄--天生自然 JAVA开发学习:Java 开发环境配置

  10. 【论文翻译】An overiview of gradient descent optimization algorithms

    这篇论文最早是一篇2016年1月16日发表在Sebastian Ruder的博客.本文主要工作是对这篇论文与李宏毅课程相关的核心部分进行翻译. 论文全文翻译: An overview of gradi ...