【发布时间】:2021-07-12 03:48:25
【问题描述】:
我有一个使用 react 开发的网站,它只有一个页面,但生产包大小为 1.11 MiB。我正在为这个应用程序使用 firestore、firebase 存储、material-UI、react-redux 运行良好,除了包大小之外一切都很好。
我使用 webpack-bundle-analyzer 来分析包大小,似乎 nodemodules 占用了很大的大小。在这里,我添加了屏幕截图。
我的 webpack 配置文件
const path = require('path');
var CompressionPlugin = require('compression-webpack-plugin');
const TerserPlugin = require("terser-webpack-plugin");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
mode: 'production',
entry: './src/public/index.js',
plugins: [
new BundleAnalyzerPlugin({
generateStatsFile : true
}),
new CompressionPlugin({
deleteOriginalAssets: false,
filename: "[path][base].gz",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
// Compress all assets, including files with `0` bytes size
// minRatio: Infinity
// Compress all assets, excluding files with `0` bytes size
// minRatio: Number.MAX_SAFE_INTEGER
minRatio: 0.8,
})
],
optimization: {
nodeEnv: 'production',
minimize: true,
concatenateModules: true,
},
module: {
rules: [{
test: /\.(jpe?g|png|gif|svg)$/,
loader: 'image-webpack-loader',
// This will apply the loader before the other ones
enforce: 'pre',
},
{
test: /\.m?js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: [
["@babel/plugin-proposal-object-rest-spread", {
"definitions": {
"process.env": {
"NODE_ENV": "\"production\""
}
}
}],
['babel-plugin-transform-imports',
{
'@material-ui/core': {
// Use "transform: '@material-ui/core/${member}'," if your bundler does not support ES modules
'transform': '@material-ui/core/esm/${member}',
'preventFullImport': true
},
'@material-ui/icons': {
// Use "transform: '@material-ui/icons/${member}'," if your bundler does not support ES modules
'transform': '@material-ui/icons/esm/${member}',
'preventFullImport': true
}
}
]
]
}
}
}
]
},
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
}
};
我不知道我在这里错过了什么来减少节点模块的大小。如果我们有任何其他减小捆绑包大小的选择,请给我一个建议。
【问题讨论】:
-
对于 lodash ,您可以通过像
import { isEqual } from 'lodash';这样的结构导入来进行一些优化,然后将sideEffect:false添加到您的包 json 中 -
你可能想探索将你的 js 文件分割成块
-
有时捆绑包很大是正常的。您可以使用延迟加载,这样客户端就不需要一次下载完整的包。您可以访问reactjs.org/docs/code-splitting.html了解更多信息。
-
@Spring 我使用了 lodash 的 mapKeys 函数,现在我为此添加了 javascript 函数并删除了 lodash 代码,它减少了 64 kb
-
也可以尝试使用
preact-compat的 Preact,这应该是 React 的 10 倍大小,同时保留了与 React 相同的 API。
标签: reactjs firebase webpack material-ui node-modules