您现在的位置是:首页 >技术教程 >前端性能优化实践网站首页技术教程
前端性能优化实践
简介前端性能优化实践
使用create-react-app创建的项目,使用react-app-rewired customize-cra 来进行webpack配置重写
完整webpack配置
config-overrides.js
const path = require('path')
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const { override, addDecoratorsLegacy } = require('customize-cra')
function resolve(dir) {
return path.join(__dirname, dir)
}
const customize = () => (config) => {
config.resolve.alias['@'] = resolve('src')
config.resolve.alias['#'] = resolve('src/IMcomponents/')
config.resolve.alias['%'] = resolve('src/assets/')
const env = process.env.REACT_APP_ENV
const isOPenAnalyzer = process.env.REACT_APP_OPEN_ANALYZER
if (env === 'prod') {
config.devtool = false;
config.externals = {
'react': 'React',
// 'react-dom': 'ReactDOM',
// 'react-router-dom': 'ReactRouterDOM'
}
// 添加js打包gzip配置
config.plugins.push(
new CompressionWebpackPlugin({
test: /.(js|css|html|svg)$/,
threshold: 1024,
minRatio: 0.8,
deleteOriginalAssets: true,
}),
)
config.optimization.splitChunks = {
chunks: "all",
minSize: 30000, //小于这个限制的会打包进Main.js
cacheGroups: {
vendors: {
test: /[\/]node_modules[\/]/,
priority: -10, // 优先级权重,层级 相当于z-index。 谁值越大权会按照谁的规则打包
name: "vendors",
},
},
}
}else {
config.devtool= "source-map"
if(isOPenAnalyzer) {
config.plugins.push( new BundleAnalyzerPlugin())
}
}
return config
};
module.exports = override(addDecoratorsLegacy(), customize())
一、环境区分
新建.env .env.development .env.production 里面的参数 直接可以使用process.env. 获取的到
二、开启gzip
// 添加js打包gzip配置
config.plugins.push(
new CompressionWebpackPlugin({
test: /.(js|css|html|svg)$/,
threshold: 1024,
minRatio: 0.8,
deleteOriginalAssets: true,
}),
)
这里有坑需要配置nginx 开启gzip
添加 gzip_static on 开启静态文件压缩
gzip on;
gzip_static on; # 开启静态文件压缩
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml;
gzip_vary on;
gzip_proxied expired no-cache no-store private auth;
gzip_disable "MSIE [1-6].";
三、设置cdn
config.externals = {
'react': 'React',
'react-dom': 'ReactDOM',
'react-router-dom': 'ReactRouterDOM'
}
index.html 引入配置全局cdn
不知道对应cdn的名字的 可以看浏览器window对象 里面有
cdnjs - The #1 free and open source CDN built to make life easier for developers
BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务
四:配置splitChunks
config.optimization.splitChunks = {
chunks: "all",
minSize: 30000, //小于这个限制的会打包进Main.js
cacheGroups: {
vendors: {
test: /[\/]node_modules[\/]/,
priority: -10, // 优先级权重,层级 相当于z-index。 谁值越大权会按照谁的规则打包
name: "vendors",
},
},
}
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。