使用dayjs替换Ant-Design组件中默认集成的moment

3,988 阅读1分钟

antd日期组件默认集成了momentjs这个日期处理库,这会使得打包的组件体积过大,可以使用dayjs替换antd组件中的moment

下载dayjs: npm i dayjs -S

下载antd-dayjs-webpack-plugin: npm i antd-dayjs-webpack-plugin -D

修改配置

webpack配置修改

const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
module.exports = {
  // ...
  plugins: [
    new AntdDayjsWebpackPlugin()
  ]
}

umi配置修改

如果是umi项目,可以参考以下配置修改

// config.ts
import { defineConfig } from 'umi';
import AntdDayjsWebpackPlugin from 'antd-dayjs-webpack-plugin';

export default defineConfig({
  // ...
  /** 使用Dayjs替换Antd的Moment,注意不要开启mfsu */
  chainWebpack: (config) => {
    config.plugin('antd-dayjs-webpack-plugin').use(AntdDayjsWebpackPlugin);
    // 如果是antdv3,使用下面的配置
    // config.plugin('antd-dayjs-webpack-plugin').use(AntdDayjsWebpackPlugin, [{ preset: 'antdv3' }]);
  },
 // ...
});

2.国际化

// ...
import { ConfigProvider } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN';
import dayjs from 'dayjs';
import dayjsLocal from 'dayjs/locale/zh-cn';
// ...
// dayjs国际化
dayjs.locale(dayjsLocal)
const App = () => {
  return (
    /* antd国际化 */
    <ConfigProvider locale={zhCN}>
      <Routes />
    </ConfigProvider>
  )
};

render(<App />, document.getElementById('root'));

3. TypeScript声明修改

若是使用TypeScript进行开发,还需要修改修改antd组件中默认的Moment声明,否则会报类型检测错误

  • 在你项目全局ts声明文件(一般以xxx.d.ts结尾)中添加以下代码
// antd-dayjs-webpack-plugin ts声明
declare module 'antd-dayjs-webpack-plugin';

// global.d.ts
declare module 'moment' {
  import { Dayjs } from 'dayjs'
  namespace moment {
    type Moment = Dayjs
  }
  export = moment
}