从0到1的移动端项目create-react-app初始化-react17
1、create-react-app 初始化项目:
npm install -g create-react-app
create-react-app my-mobile-app
cd my-mobile-app
npm start
安装antd-mobile
npm install antd-mobile --save
2、入口页面 (html 或 模板) 相关设置:
<!DOCTYPE html>
<html>
<head>
<!-- set `maximum-scale` for some compatibility issues -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<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></body>
</html>
3、页面使用antd-mobile的Button组件
//src/App.js
import './App.css';
import {
Button } from 'antd-mobile';
import 'antd-mobile/dist/antd-mobile.css';
function App() {
return (
<div className="App">
<Button type="primary">Start</Button>
</div>
);
}
export default App;
4、配置按需加载
npm install react-app-rewired customize-cra --save-dev
/* 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",
}
//然后在项目根目录创建一个 config-overrides.js 用于修改默认配置。
module.exports = function override(config, env) {
// do stuff with the webpack config...
return config;
};
// babel-plugin-import 是一个用于按需加载组件代码和样式的 babel 插件
npm install babel-plugin-import --save-dev
//然后修改 config-overrides.js 文件
+ const {
override, fixBabelImports } = require('customize-cra');
- module.exports = function override(config, env) {
- // do stuff with the webpack config...
- return config;
- };
+ module.exports = override(
+ fixBabelImports('import', {
+ libraryName: 'antd-mobile',
+ style: 'css',
+ }),
+ );
修改src/App.js文件,去掉样式引入,修改后的文件内容:
import './App.css'
import {
Button } from 'antd-mobile'
function App() {
return (
<div className="App">
<Button type="primary">Start</Button>
</div>
)
}
export default App
5、运行,npm start