1.create-react-app的按需引入antd:
-
使用
npx create-react-app 项目名
初始化项目后 -
执行
yarn add @craco/craco
-
修改项目目录文件
package.json
/* package.json */ "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", - "test": "react-scripts test", + "start": "craco start", + "build": "craco build", + "test": "craco test", }
-
执行
yarn add babel-plugin-import
和yarn add craco-less
完成二者的安装,如果需要装饰器则还需要执行yarn add @babel/plugin-proposal-decorators
-
在项目根目录创建一个
craco.config.js
用于修改默认配置/* `craco.config.js` */ const CracoLessPlugin = require('craco-less'); module.exports = { plugins: [ { plugin: CracoLessPlugin, options: { lessLoaderOptions: { lessOptions: { modifyVars: { '@primary-color': 'red' }, //🚀设置primary颜色为红色red javascriptEnabled: true, }, }, }, }, ], babel:{ plugins: [ [ "import", { "libraryName": "antd", "libraryDirectory": "es", "style": true //设置为true即是less } ], [ "@babel/plugin-proposal-decorators", // 🚀使用装饰器的配置 { "legacy": true } ] ] }, }
-
在App.js文件中引入antd的组件进行测试
/* src/App.js */ import './App.css'; import { Button } from "antd"; function App() { return ( <div className="App"> <header className="App-header"> <Button type="primary">登 录</Button> </header> </div> ); } export default App;
🚀更多关于create-react-app
的问题参照官网:ant.design/docs/react/…