angular 打包优化 之 moment.js

项目中用到了 moment.js, 但是 编译后使用 webpack-bundle-analyzer 发现 moment.js 的体积比较大, 大部分是 locale 文件, 实际上我只需要 zh-cn 这个语言包。

占比截图:


angular 打包优化 之 moment.js_第1张图片
before.png

moment.js 并不是一个现代化的模块化的库, 无法对其进行摇树优化。

解决办法:

  • 选用其他替代方案。 将 moment.js 替换为 data-fns
  • 使用 webpack ContextReplacementPlugin + @angular-builders/custom-webpack

这里介绍第二种方案, 对代码改动最小。

extra-webpack.config.js

'use strict';

const webpack = require('webpack');

// https://webpack.js.org/plugins/context-replacement-plugin/
module.exports = {
  plugins: [new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn/)]
};

angular.json

"projects": {
    "moment-locale-ignore": {
      ...
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./extra-webpack.config.js",
              "replaceDuplicatePlugins": true,
              "mergeStrategies": {
                "externals": "prepend"
              }
            }
          ...
          }
        }
      }
    }
    }
  }

这样 打包后的 moment.js 体积就缩小很多了

angular 打包优化 之 moment.js_第2张图片
after.png

最后附上 Github 库

你可能感兴趣的:(angular 打包优化 之 moment.js)