返回
从零到一:UMI3 + React Vant2 + VW 布局助力移动端项目搭建
前端
2024-01-02 05:58:53
导语
移动端项目的开发正日益成为主流,而 UMI3、React Vant2 和 VW 布局作为三款强大的工具,可以帮助开发者更高效、更轻松地构建移动端项目。本文将介绍如何使用这三款工具搭建一个移动端项目,并分享一些实践经验和技巧。
正文
一、UMI3 项目搭建
- 安装 UMI3
npm install umi -g
- 创建项目
umi new my-project
- 启动项目
cd my-project
npm start
二、React Vant2 集成
- 安装 React Vant2
npm install react-vant@2.0.0-beta.24
- 在
src/App.js
中引入 React Vant2
import { Button } from 'react-vant';
function App() {
return (
<div className="App">
<Button>Button</Button>
</div>
);
}
export default App;
三、VW 布局适配
- 在
src/App.css
中添加 VW 布局样式
html {
font-size: 100vw;
}
- 在组件中使用 VW 单位
import styled from 'styled-components';
const MyComponent = styled.div`
width: 10vw;
height: 10vw;
`;
四、路由配置
- 在
src/config/routes.ts
中配置路由
export default [
{
path: '/',
component: '@/pages/index',
},
{
path: '/about',
component: '@/pages/about',
},
];
- 在
src/App.js
中使用路由
import { Router, Route } from 'umi';
function App() {
return (
<div className="App">
<Router>
<Route path="/" exact component={IndexPage} />
<Route path="/about" component={AboutPage} />
</Router>
</div>
);
}
export default App;
五、Typescript 配置
- 在
package.json
中添加 Typescript 支持
{
"scripts": {
"start": "umi dev",
"build": "umi build",
"test": "umi test"
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "4.0.3",
"umi": "^3.2.20",
"react-vant": "^2.0.0-beta.24",
"@types/react": "^16.9.19",
"@types/react-dom": "^16.9.8"
},
"devDependencies": {
"@types/node": "^14.14.20",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"eslint": "^7.32.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-react": "^7.29.4",
"eslint-plugin-react-hooks": "^4.2.0",
"typescript": "^4.4.4"
}
}
- 在
tsconfig.json
中配置 Typescript 编译选项
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"jsx": "react",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"baseUrl": "./src",
"paths": {
"@/*": ["./*"]
}
},
"include": [
"src"
],
"exclude": [
"node_modules"
]
}
六、请求封装
- 在
src/utils/request.ts
中封装请求
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
});
export function get(url: string, params?: object) {
return instance.get(url, { params });
}
export function post(url: string, data?: object) {
return instance.post(url, data);
}
- 在组件中使用请求封装
import { get } from '@/utils/request';
const MyComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
get('/api/data').then(res => {
setData(res.data);
});
}, []);
return (
<div>
{data.map(item => <li key={item.id}>{item.name}</li>)}
</div>
);
};
export default MyComponent;
结语
本文介绍了如何使用 UMI3、React Vant2 和 VW 布局搭建一个移动端项目,并分享了一些实践经验和技巧。希望对您有所帮助。