认识
安装
- NPM
- Yarn
npm install antd
yarn add antd
引入
方式一、普通引入
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
按需引入
-
配置
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',
],
},
}); -
任意
.jsx
或者.tsx
中使用import React from 'react';
import {Button} from 'antd';
function App() {
return (
<div>
<Button>按钮</Button>
</div>
);
}
export default App;
方式三、create-react-app
按需引入
-
安装
react-app-rewired
,用于自定义配置webpack
-
安装
customize-cra
,用于支持新版create-react-app
项目 -
安装
babel-plugin-import
,用于按需加载组件代码和样式 -
根目录新建
config-overrides.js
const { override, fixBabelImports } = require("customize-cra");
module.exports = override(
fixBabelImports("import", {
libraryName: "antd",
libraryDirectory: "es",
style: "css",
})
); -
修改
package.json
,通过react-app-rewired
启动服务"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-scripts test",
"eject": "react-scripts eject"
} -
任意
.jsx
或者.tsx
中使用import { Button } from 'antd';
<Button type="primary">Primary</Button>