1. 程式人生 > 其它 >解決專案中使用momentJS檔案 體積過大的問題

解決專案中使用momentJS檔案 體積過大的問題

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/), ], };

值得注意的是,這樣你就不需要在程式碼中再次引入本地檔案了,