create-react-app 使用 antd,按需加载

前言

使用 create-react-app 创建的 react 项目,结合使用 antd 时,官网文档介绍了按需加载需要使用 babel-plugin-import 来配合,如果你的项目还没有执行 npm run eject,则使用官网推荐的配置即可,由于我已经 eject 过,记录下我的配置。

过程
1、安装 yarn add babel-plugin-import 或者 npm -s install babel-plugin-import
2、给 webpack 的 babel-loader plugins 加上 babel-plugin-import

需要修改两个文件 /config/webpack.config.prod.js/config/webpack.config.dev.js (修改的内容一样),找到加载 babel-loader 的地方,往他的 plugins 加入如下代码

  [
    require.resolve('babel-plugin-import'),// 导入 import 插件
    {
      libraryName: 'antd',   //暴露antd
      style: 'css'
    }
  ]
复制代码

最后形成的配置如下(create-react-app 版本不同最后的配置可能不一样,原理一样):

  // Process application JS with Babel.
  // The preset includes JSX, Flow, and some ESnext features.
  {
    test: /\.(js|mjs|jsx|ts|tsx)$/,
    include: paths.appSrc,
    loader: require.resolve('babel-loader'),
    options: {
      customize: require.resolve(
        'babel-preset-react-app/webpack-overrides'
      ),

      plugins: [
        [
          require.resolve('babel-plugin-named-asset-import'),
          {
            loaderMap: {
              svg: {
                ReactComponent: '@svgr/webpack?-prettier,-svgo![path]',
              },
            },
          },
        ],
        [
          require.resolve('babel-plugin-import'),// 导入 import 插件
          {
            libraryName: 'antd',   //暴露antd
            style: 'css'
          }
        ],
      ],
      // This is a feature of `babel-loader` for webpack (not Babel itself).
      // It enables caching results in ./node_modules/.cache/babel-loader/
      // directory for faster rebuilds.
      cacheDirectory: true,
      // Don't waste time on Gzipping the cache
      cacheCompression: false,
    },
  }
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值