create-react-app中antd按需引入

341 阅读1分钟

1.create-react-app的按需引入antd:

  1. 使用npx create-react-app 项目名初始化项目后

  2. 执行yarn add @craco/craco

  3. 修改项目目录文件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",
    }
    
  4. 执行 yarn add babel-plugin-importyarn add craco-less 完成二者的安装,如果需要装饰器则还需要执行 yarn add @babel/plugin-proposal-decorators

  5. 在项目根目录创建一个 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
                 }
               ]
            ]
        },
    }
    
  6. 在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/…