1.第一种方式
1.1.下载
npm install babel-plugin-import --save
1.2.配置文件
//修改package.json{ "name": "my-app", "version": "0.1.0", "private": true, "dependencies": { "@testing-library/jest-dom": "^5.11.4", "@testing-library/react": "^11.1.0", "@testing-library/user-event": "^12.1.10", "antd-mobile": "^2.3.4", "babel-plugin-import": "^1.13.3", "eject": "^0.0.4", "react": "^17.0.2", "react-dom": "^17.0.2", "react-scripts": "4.0.3", "web-vitals": "^1.0.1" }, //配置这里 "plugins": [ [ "import", { "libraryName": "antd-mobile", "style": "css" } ] ] , "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" }, "eslintConfig": { "extends": [ "react-app", "react-app/jest" ] }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }}
1.3.使用
import { Button } from 'antd-mobile';import 'antd-mobile/dist/antd-mobile.css'import './App.css';function App() { return ( <div className="App"> <Button type="primary">Start</Button> </div> );}export default App;
2.第二种方式
2.1下载
npm install react-app-rewired customize-cra --save-devnpm install babel-plugin-import --save-dev
2.2修改配置文件
//修改package.json中的script属性 "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test --env=jsdom" },
2.3新增配置文件
//在根目录下新增 config-overrides.js const { override, fixBabelImports } = require('customize-cra'); module.exports = override( fixBabelImports('import', { libraryName: 'antd-mobile', style: 'css', }),);
2.4使用
import { Button } from 'antd-mobile'; //实现按需加载import 'antd-mobile/dist/antd-mobile.css'function App() { return ( <div className="App"> <Button type="primary">hello</Button> </div> );}export default App;