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

前言

使用 create-react-app 建立的 react 項目,結合使用 antd 時,官網文檔介紹了按需加載須要使用 babel-plugin-import 來配合,若是你的項目尚未執行 npm run eject,則使用官網推薦的配置便可,因爲我已經 eject 過,記錄下個人配置。javascript

過程

一、安裝 yarn add babel-plugin-import 或者 npm -s install babel-plugin-import
二、給 webpack 的 babel-loader plugins 加上 babel-plugin-import

須要修改兩個文件 /config/webpack.config.prod.js/config/webpack.config.dev.js (修改的內容同樣),找到加載 babel-loader 的地方,往他的 plugins 加入以下代碼css

[
    require.resolve('babel-plugin-import'),// 導入 import 插件
    {
      libraryName: 'antd',   //暴露antd
      style: 'css'
    }
  ]
複製代碼

最後造成的配置以下(create-react-app 版本不一樣最後的配置可能不同,原理同樣):java

// 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,
    },
  }
複製代碼
相關文章
相關標籤/搜索