likes
comments
collection
share

Antd moment.js打包体积优化之路

作者站长头像
站长
· 阅读数 50

背景:CR时候有同事提出建议,可以用day.js替换moment.js,可以实现200k->20k的跨越优化,后面也会提到具体实现及坑

moment.js打包体积优化解决方法

一、使用day.js替换moment.js

方法有三种,我使用了其中一种使用插件 antd-dayjs-webpack-plugin 直接在打包时候转换。其他方法详见antd给出的方法:https://ant.design/docs/react...

// webpack-config.js
import AntdDayjsWebpackPlugin from 'antd-dayjs-webpack-plugin';

module.exports = {
  // ...
  plugins: [new AntdDayjsWebpackPlugin()],
};

注:但是这个方法会造成如下图这个问题!Antd moment.js打包体积优化之路此插件的issues也有同学遇到这个问题了,暂时没有解决方法,issues详见:https://github.com/ant-design...

二、直接使用dayjs

此方法在antd框架内使用后会报出必须要使用moment类型的错误,故也放弃这种方法

三、直接优化moment的打包体积

这个方法也是最后决定用并且无bug的一个方法步骤如下:

  • 直接使用webpackContextReplacementPlugin方法,忽略moment包中的其他无用的locale,只留下中文的locale

    const webpack = require('webpack');
    module.exports = {
    //...
    plugins: [
      // load `moment/locale/ja.js` and `moment/locale/it.js`
      new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn/),
    ],
    };
  • 打包体积的对比Antd moment.js打包体积优化之路

忽略打包还有个方法:IgnorePlugin,与上面写到的方法稍有不同,详见:https://github.com/jmblog/how...可以看到locale包都被忽略了,达到了减少了打包体积的目的