我正在尝试减小bundle.js的大小。这是我用于生产的webpack配置:
module.exports = () => {
return {
entry: ['babel-polyfill', './src/app.js'],
output: {
path: path.join(__dirname, 'public', 'dist'),
filename: 'bundle.js',
chunkFilename: '[name].js'
},
optimization: {
runtimeChunk: true,
splitChunks: {
chunks: 'all',
minSize: 50000,
maxSize: 250000,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
name: "vendors",
priority: -10
},
}
},
minimizer: [
new UglifyJSPlugin({
uglifyOptions: {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
comparisons: false,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
},
cache: true,
parallel: true,
sourceMap: true
}),
new OptimizeCSSAssetsPlugin({})
]
},
module: {
rules: [{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}]
},
plugins: [
new webpack.DefinePlugin({/*env variables*/}),
new MiniCssExtractPlugin({
filename: 'styles.css',
}),
new HtmlWebpackPlugin({ template: 'index.ejs', filename: path.join(__dirname, 'public', 'index.html')}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
],
devtool: 'source-map'
};
};
我的应用的结构类似于经典的React / Redux应用:
|-src
|-|-app.js
|-|-actions
|-|-components
|-|-helpers
|-|-routers
|-|-selectors
|-|-store
使用此webpack配置,我设法将css提取出来并分成最大250kb的块。我也减少了片刻的大小。 经过所有这些努力,我的入口点仍然是583Kb。
我还能做什么? 我尝试了延迟加载应用程序的一部分,但没有成功。因此,如果您有一个React应用程序的延迟加载示例,那就太好了。
答案 0 :(得分:0)
我有webpack 6.0.1。基于documentation,我使用以下插件:
我测试过,对webpack.config.js使用以下配置思路。您可以针对以下设置测试您的配置:
//webpack.config.js
module.exports = {
...
devtool: 'cheap-module-source-map',
...
plugins : [
...
new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.HashedModuleIdsPlugin({
hashFunction: 'sha256',
hashDigest: 'hex',
hashDigestLength: 4
}),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
...
optimization: {
namedModules: false,
namedChunks: false,
nodeEnv: 'production',
flagIncludedChunks: true,
occurrenceOrder: true,
sideEffects: true,
usedExports: true,
concatenateModules: true,
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
chunks: 'all'
}
},
minSize: 30000,
maxAsyncRequests: 5,
maxAsyncRequests: 3,
},
noEmitOnErrors: true,
minimize: true,
minimizer: [
// we specify a custom UglifyJsPlugin here to get source maps in production
new UglifyJsPlugin({
cache: true,
parallel: true,
uglifyOptions: {
compress: false,
ecma: 6,
mangle: true
},
sourceMap: true
})
],
removeAvailableModules: true,
removeEmptyChunks: true,
mergeDuplicateChunks: true,
},
...
}