References:

customize-cra

react-app-rewired

babel-plugin-import

Create a project:Github Demo)

npx create-react-app override-cra --use-yarn
Copy the code

Install dependencies:

cd override-cra
For the less-loader version, see q&a at the bottom of the article
yarn add antd
yarn add customize-cra react-app-rewired babel-plugin-import less less-loader -D
Copy the code

Json in the same directory as package.jsonconfig-overrides.jsfile

const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  // antd load on demand
  fixBabelImports('import', {
    libraryName: 'antd'.libraryDirectory: 'es'.style: true.// The default value is CSS
  }),
  / / configure less - loader
  addLessLoader({
    // lessOptions must be added to the less-loader of a higher version
    // lessOptions: {
    javascriptEnabled: true.modifyVars: {
      // '@primary-color': '#1DA57A', // customize antd theme
    },
    // },}));Copy the code

Modify package.json scripts :(react-scripts -> react-app-rewired)

"scripts": {
  // "start": "react-scripts start",
  "start": "react-app-rewired start".// "build": "react-scripts build",
  "build": "react-app-rewired build".// "test": "react-scripts test",
  "test": "react-app-rewired test",},Copy the code

Q&A:

Error: / node_modules/antd/es/button/style/index. The less (. / node_modules/CSS - loader/dist/CJS. Js?? ref--5-oneOf-8-1! ./node_modules/postcss-loader/src?? postcss! ./node_modules/resolve-url-loader?? ref--5-oneOf-8-3! ./node_modules/less-loader/dist/cjs.js?? ref--5-oneOf-8-4! ./node_modules/antd/es/button/style/index.less) TypeError: This. GetOptions is not a function Cause: The version of less-loader installed is too high. Solution: yarn remove less-loader yarn add [email protected]Copy the code