1.第一种方式

1.1.下载

  1. npm install babel-plugin-import --save

1.2.配置文件

  1. //修改package.json
  2. {
  3. "name": "my-app",
  4. "version": "0.1.0",
  5. "private": true,
  6. "dependencies": {
  7. "@testing-library/jest-dom": "^5.11.4",
  8. "@testing-library/react": "^11.1.0",
  9. "@testing-library/user-event": "^12.1.10",
  10. "antd-mobile": "^2.3.4",
  11. "babel-plugin-import": "^1.13.3",
  12. "eject": "^0.0.4",
  13. "react": "^17.0.2",
  14. "react-dom": "^17.0.2",
  15. "react-scripts": "4.0.3",
  16. "web-vitals": "^1.0.1"
  17. },
  18. //配置这里
  19. "plugins": [
  20. [
  21. "import",
  22. {
  23. "libraryName": "antd-mobile",
  24. "style": "css"
  25. }
  26. ]
  27. ] ,
  28. "scripts": {
  29. "start": "react-scripts start",
  30. "build": "react-scripts build",
  31. "test": "react-scripts test",
  32. "eject": "react-scripts eject"
  33. },
  34. "eslintConfig": {
  35. "extends": [
  36. "react-app",
  37. "react-app/jest"
  38. ]
  39. },
  40. "browserslist": {
  41. "production": [
  42. ">0.2%",
  43. "not dead",
  44. "not op_mini all"
  45. ],
  46. "development": [
  47. "last 1 chrome version",
  48. "last 1 firefox version",
  49. "last 1 safari version"
  50. ]
  51. }
  52. }

1.3.使用

  1. import { Button } from 'antd-mobile';
  2. import 'antd-mobile/dist/antd-mobile.css'
  3. import './App.css';
  4. function App() {
  5. return (
  6. <div className="App">
  7. <Button type="primary">Start</Button>
  8. </div>
  9. );
  10. }
  11. export default App;

2.第二种方式

2.1下载

  1. npm install react-app-rewired customize-cra --save-dev
  2. npm install babel-plugin-import --save-dev

2.2修改配置文件

  1. //修改package.json中的script属性
  2. "scripts": {
  3. "start": "react-app-rewired start",
  4. "build": "react-app-rewired build",
  5. "test": "react-app-rewired test --env=jsdom"
  6. },

2.3新增配置文件

  1. //在根目录下新增 config-overrides.js
  2. const { override, fixBabelImports } = require('customize-cra');
  3. module.exports = override(
  4. fixBabelImports('import', {
  5. libraryName: 'antd-mobile',
  6. style: 'css',
  7. }),
  8. );

2.4使用

  1. import { Button } from 'antd-mobile'; //实现按需加载
  2. import 'antd-mobile/dist/antd-mobile.css'
  3. function App() {
  4. return (
  5. <div className="App">
  6. <Button type="primary">hello</Button>
  7. </div>
  8. );
  9. }
  10. export default App;