背景: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.jsimport AntdDayjsWebpackPlugin from 'antd-dayjs-webpack-plugin';module.exports = {  // ...  plugins: [new AntdDayjsWebpackPlugin()],};

注:然而这个办法会造成如下图这个问题!

此插件的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/),],};
  • 打包体积的比照

疏忽打包还有个办法:IgnorePlugin,与下面写到的办法稍有不同,详见:https://github.com/jmblog/how...
能够看到locale包都被忽略了,达到了缩小了打包体积的目标