跳到主要内容

认识

安装


npm install antd @ant-design/icons @ant-design/pro-components -S

引入


方式一、普通引入

import {Button} from 'antd';
import 'antd/dist/antd.css';

class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Button>按钮</Button>
</div>
);
}
}

export default App;

方式二、vite 按需引入

  1. 配置vite.config.js

    import Path from 'path';
    import {defineConfig} from 'vite';
    import ReactPlugin from '@vitejs/plugin-react';
    import {createStyleImportPlugin} from 'vite-plugin-style-import';

    export default ({comman, code}) =>
    defineConfig({
    css: {
    preprocessorOptions: {
    less: {
    javascriptEnabled: true,
    },
    },
    },
    plugins: [
    ReactPlugin(),
    createStyleImportPlugin({
    libs: [
    {
    libraryName: 'antd',
    esModule: true,
    resolveStyle: (name) => `antd/es/${name}/style/index`,
    },
    ],
    }),
    ],
    resolve: {
    alias: {
    '~antd': 'antd',
    '@': Path.resolve(__dirname, 'src'),
    },
    extensions: [
    '.js',
    '.ts',
    '.jsx',
    '.tsx',
    '.json',
    '.scss',
    '.less',
    ],
    },
    });
  2. 任意 .jsx 或者 .tsx 中使用

    import React from 'react';
    import {Button} from 'antd';

    function App() {
    return (
    <div>
    <Button>按钮</Button>
    </div>
    );
    }

    export default App;

方式三、create-react-app 按需引入

  1. 安装react-app-rewired,用于自定义配置webpack

  2. 安装customize-cra,用于支持新版create-react-app项目

  3. 安装babel-plugin-import,用于按需加载组件代码和样式

  4. 根目录新建config-overrides.js

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

    module.exports = override(
    fixBabelImports("import", {
    libraryName: "antd",
    libraryDirectory: "es",
    style: "css",
    })
    );
  5. 修改package.json,通过react-app-rewired启动服务

    "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
    }
  6. 任意 .jsx 或者 .tsx 中使用

    import { Button } from 'antd';

    <Button type="primary">Primary</Button>