美文网首页
angular 打包优化 之 moment.js

angular 打包优化 之 moment.js

作者: 萧哈哈 | 来源:发表于2018-09-10 15:46 被阅读429次

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

    占比截图:


    before.png

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

    解决办法:

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

    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 体积就缩小很多了

    after.png

    最后附上 Github 库

    相关文章

      网友评论

          本文标题:angular 打包优化 之 moment.js

          本文链接:https://www.haomeiwen.com/subject/mipsgftx.html