我正在尝试将构建文件( main.js )的大小减小到500kb或更小。
最初它是1.2MB,通过一些代码拆分和webpack,我设法将其减少到600kb左右,但我需要再减少100kb。 我是webpack的新手,希望收到您的反馈。
下面您可以找到我的 webpack.prodduction.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')
console.log(`Building for: ${process.env.NODE_ENV}`)
module.exports = {
module: {
rules: [
{
test: /.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}, {
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=100000' },
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
options: {
presets: [
['@babel/preset-env', {
useBuiltIns: false,
modules: false
}]
],
plugins: [
'@babel/plugin-transform-runtime',
'@babel/plugin-proposal-class-properties',
'inline-react-svg'
]
},
loader: 'babel-loader'
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.module\.s(a|c)ss$/,
loader: [
{
loader: 'style-loader',
options: {
attrs: { class: 'BasebotTag' }
}
},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]',
camelCase: true
}
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
},
{
test: /\.s(a|c)ss$/,
exclude: /\.module.(s(a|c)ss)$/,
loader: [
{
loader: 'style-loader',
options: {
attrs: { class: 'BasebotTag' }
}
},
'css-loader',
{
loader: 'sass-loader'
}
]
}
]
},
resolve: {
extensions: ['.js', '.jsx', '.scss']
},
plugins: [
new UglifyJSPlugin(),
new LodashModuleReplacementPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
new webpack.optimize.ModuleConcatenationPlugin(),
new MiniCssExtractPlugin({
filename: '[name].[hash].css',
chunkFilename: '[id].[hash].css'
}),
new LodashModuleReplacementPlugin({
caching: true,
cloning: true
})
]
}
编辑: 这是我的构建脚本:
"build": "NODE_ENV=production webpack --config webpack.production.config",
答案 0 :(得分:1)
您正在使用url-loader
内联最大为0.1MB(100000字节)的图像和其他资产。拥有此上限大小的许多资产并不需要显着增加捆绑包的大小。实际上,减少此限制并取消内联仅100KB的一项资产就意味着您达到了目标捆绑包的大小。
我建议仅内联小于10KB(10000字节)的资产。需要时,所有大于此大小的内容都可以通过HTTP请求获取。
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
loader: 'url-loader?limit=10000' }, // <= lower the limit here to 10000
}