React按需加载antd-mobile
1.修改index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<meta name="theme-color" content="#000000" />
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<title>React App</title>
<script src="https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js"></script>
<script>
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
if(!window.Promise) {
document.writeln('<script src="https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js"'+'>'+'<'+'/'+'script>');
}
</script>
</head>
<body>
<div id="root"></div>
</body>
</html>
2.安装antd-mobile依赖包
npm install antd-mobile --save
3.按需加载
npm i --save babel-plugin-import
npm i react-app-rewired --save-dev
修改package.json文件
/* package.json */
"scripts": {
- "start": "react-scripts start",
+ "start": "react-app-rewired start",
- "build": "react-scripts build",
+ "build": "react-app-rewired build",
- "test": "react-scripts test --env=jsdom",
+ "test": "react-app-rewired test --env=jsdom",
}
// 下面的我已经打包好了
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。
官方给出的config-override.js为
const { injectBabelPlugin } = require('react-app-rewired');
module.exports = function override(config, env) {
config = injectBabelPlugin(
['import', { libraryName: 'antd-mobile', libraryDirectory: 'es', style: 'css' }],
config,
);
return config;
};
但是你会报这样的错误
这时你需要安装这些依赖
npm i customize-cra --save
npm i less-loader --save
主要因为injectBabelPlugin is not a function
查阅资料发现react-scripts 升级到 2.1.2 以后破坏了 react-app-rewired,react-app-rewired的新版本删除所有方法injectBabelPlugin,这些方法被移动到一个名为'customize-cra'的新包中了
修改方法:
1.确保已经下载customize-cra,less-loader
2.修改config-overrides文件为
const {
override,
fixBabelImports,
// addLessLoader,
} = require("customize-cra");
module.exports = override(
fixBabelImports("import", {
libraryName: "antd-mobile", libraryDirectory: "es", style: 'css' // change importing css to less
}),
);
最后在App.js中引入
import React, { Component } from 'react'
import { Button} from 'antd-mobile';
export default class App extends Component {
render() {
return (
<div>
<Button type="primary">按钮</Button>
</div>
)
}
}
npm start