1、体积过大的原因:
当你在代码中写了
var moment = require('moment')
然后再用webpack打包, 打出来的包会比你想象中的大很多,因为打包结果包含了各地的local文件。
2、优化方案:
(1)IgnorePlugin插件
IgnorePlugin
的原理是会移除moment的所有本地文件,因为我们很多时候在开发中根本不会使用到。 这个插件的使用方式如下:
const webpack = require('webpack'); module.exports = { //... plugins: [ // 忽略 moment.js的所有本地文件 new webpack.IgnorePlugin(/^./locale$/, /moment$/), ], };
那么你可能会有疑问,所有本地文件都被移除了,但我想要用其中的一个怎么办。不用担心,你依然可以在代码中这样使用:
const moment = require('moment'); require('moment/locale/ja'); moment.locale('ja'); ...
(2)ContextReplacementPlugin插件
const webpack = require('webpack'); module.exports = { //... plugins: [ // 只加载 `moment/locale/ja.js` 和 `moment/locale/it.js` new webpack.ContextReplacementPlugin(/moment[/\]locale$/, /ja|it/), ], };
值得注意的是,这样你就不需要在代码中再次引入本地文件了,