我正在优化我的react应用程序包。当前大小为1.4MB。在路由器中实现了延迟加载。当在localhost上运行该应用程序时,我可以在浏览器的"网络"选项卡中看到懒惰加载工作得很好,我在浏览器中看到了第一个初始块加载和渲染,然后剩下的1.4MB就来了。当我创建一个生产捆绑包并将其部署到服务器时,问题就来了,整个1.4MB的负载,然后可以看到渲染。
在创建生产捆绑包的过程中是否缺少什么?如何检查懒惰加载是否在服务器上工作?
Webpack.config.js
const path = require('path');
const { resolve } = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var CompressionPlugin = require('compression-webpack-plugin');
process.env.BABEL_ENV = 'production';
process.env.NODE_ENV = 'production';
module.exports = {
devtool: 'cheap-module-source-map',
entry: './src/index.jsx',
resolve: {
fallback: { crypto: false },
extensions: ['.js', '.jsx', '.json', '.wasm'],
enforceExtension: false,
alias: {
process: resolve('node_modules/process')
}
},
devServer: {
historyApiFallback: true,
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
module: {
rules: [
{
test: /.js$|jsx/,
loader: 'babel-loader',
exclude: /node_modules[/\\](?!(mesh-component-library|mesh-icon-library)[/\\]).*/
},
{
test: /.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader'
}
]
},
{
test: /.sass$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'sass-loader'
}
]
},
{
test: /.(png|jp(e*)g|svg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: 'images/[hash]-[name].[ext]'
}
}
]
}
]
},
plugins: [
new webpack.ProvidePlugin({ process: 'process/browser' }),
new HtmlWebpackPlugin({ template: './public/index.html' }),
new MiniCssExtractPlugin({ filename: 'styles.css' }),
new webpack.EnvironmentPlugin({
NODE_ENV: process.env.BABEL_ENV,
BABEL_ENV: process.env.NODE_ENV
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new CompressionPlugin({
algorithm: "gzip",
threshold: 10240,
minRatio: 0.8
})
]
};
包.json
"scripts": {
"test": "jest --watchAll=false --coverage",
"testWithResults": "jest --json --outputFile=./testResults.json",
"start": "webpack-dev-server --mode development --config webpack.config.js --open --port 4000",
"build": "webpack --mode production --config webpack.config.js",
"eslint": "eslint src/**/*.js*"
},
尝试配置webpack SplitChunksPlugin以包含所有。
将此部分添加到您的webpack配置中。
optimization: {
splitChunks: {
chunks: 'all',
}
}
我建议使用Webpack捆绑包分析器,它帮助我区分了最近实现动态加载前后的捆绑包大小。实现非常简单,他们在文档中已经提到过。很容易理解尺寸上的差异,而且一切都是视觉上的。希望这能有所帮助!