知识点

  • 构架工具 Vite。
  • 前端框架 React 和路由 react-router-dom。
  • CSS 预加载器 Less。
  • HTTP 请求库 axios。
  • 移动端分辨率适配 flexible。
  • 跨域代理。

    一键生成项目

    1. npm init @vitejs/app account-book-react -- --template react
    安装完 node_modules 之后,通过 npm run dev 启动项目,如下所示代表成功了:
    image.png

    添加路由

    安装 react-router-dom
    1. npm i react-router-dom -S
    在项目 src 目录下新增 container 目录用于放置页面组件,再在 container 下新增两个目录分别是 Index 和 About ,添加如下内容: ```javascript // Index/index.jsx import React from ‘react’

export default function Index() { return

Index
}

// About/index.jsx import React from ‘react’

export default function About() { return

About
}

  1. 再来新建 src/router/index.js 配置路由数组,添加如下内容:
  2. ```javascript
  3. // router/index.js
  4. import Index from '../container/Index'
  5. import About from '../container/About'
  6. const routes = [
  7. {
  8. path: "/",
  9. component: Index
  10. },
  11. {
  12. path: "/about",
  13. component: About
  14. }
  15. ];
  16. export default routes

在 App.jsx 引入路由配置,实现切换浏览器路径,显示相应的组件:

  1. // App.jsx
  2. import React, { useState } from 'react'
  3. import {
  4. BrowserRouter as Router,
  5. Switch,
  6. Route
  7. } from "react-router-dom"
  8. import routes from '../src/router'
  9. function App() {
  10. return <Router>
  11. <Switch>
  12. {
  13. routes.map(route => <Route exact key={route.path} path={route.path}>
  14. <route.component />
  15. </Route>)
  16. }
  17. </Switch>
  18. </Router>
  19. }
  20. export default App

启动项目 npm run dev,如下图所示:
image.png

引入 Zarm UI 组件库

首先通过如下指令安装它:

  1. npm install zarm -S

修改 App.jsx 的代码,全局引入样式和中文包:

  1. import React, { useState } from 'react'
  2. import {
  3. BrowserRouter as Router,
  4. Switch,
  5. Route
  6. } from "react-router-dom"
  7. import { ConfigProvider } from 'zarm'
  8. import zhCN from 'zarm/lib/config-provider/locale/zh_CN'
  9. import 'zarm/dist/zarm.css'
  10. import routes from '../src/router'
  11. function App() {
  12. return <Router>
  13. <ConfigProvider primaryColor={'#007fff'} locale={zhCN}>
  14. <Switch>
  15. {
  16. routes.map(route => <Route exact key={route.path} path={route.path}>
  17. <route.component />
  18. </Route>)
  19. }
  20. </Switch>
  21. </ConfigProvider>
  22. </Router>
  23. }
  24. export default App

优化组件库按需引入

使用全局引入组件库,打包项目以后,css 静态资源就 168.22kb 了,使用按需引入的方式来优化一下
首先我们安装一个插件:

  1. npm i vite-plugin-style-import -D

然后在 vite.config.js 配置文件内添加如下内容:

  1. export default defineConfig({
  2. plugins: [reactRefresh(), styleImport(
  3. {
  4. libs: [
  5. {
  6. libraryName: 'zarm',
  7. esModule: true,
  8. resolveStyle: (name) => {
  9. return `zarm/es/${name}/style/css`;
  10. },
  11. }
  12. ]
  13. }
  14. )],
  15. })

再次打包以后,css 提及从 168.22kb -> 35.22kb。这种方式也是前端性能优化的其中一种。

配置 CSS 预处理器 Less

安装 less 插件包,npm i less -D,因为上述配置我们使用的是 less,并且我们需要配置 javascriptEnabled 为 true,支持 less 内联 JS。
修改 vite.config.js,如下:

  1. {
  2. plugins: [...]
  3. css: {
  4. modules: {
  5. localsConvention: 'dashesOnly'
  6. },
  7. preprocessorOptions: {
  8. less: {
  9. // 支持内联 JavaScript
  10. javascriptEnabled: true,
  11. }
  12. }
  13. },
  14. }

并且添加了 css modules 配置,这样我们就不用担心在项目中,自定义的样式重名的风险,我们尝试在 /container/Index 目录下添加样式文件 style.module.less,并且在 /container/Index/index.jsx 中引入它,如下:

  1. .index {
  2. span {
  3. color: red;
  4. }
  5. }
  1. // Index/index.jsx
  2. import React from 'react'
  3. import { Button } from 'zarm'
  4. import s from './style.module.less'
  5. export default function Index() {
  6. return <div className={s.index}>
  7. <span>样式</span>
  8. <Button theme='primary'>按钮</Button>
  9. </div>
  10. }

移动端项目适配 rem

安装 lib-flexible:

  1. npm i lib-flexible -S

并在 main.jsx 中引入它:

  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. import 'lib-flexible/flexible'
  4. import './index.css'
  5. import App from './App'
  6. ReactDOM.render(
  7. <React.StrictMode>
  8. <App />
  9. </React.StrictMode>,
  10. document.getElementById('root')
  11. )

然后再安装一个 postcss-pxtorem,它的作用是在你编写完 css 后,将你的单位自动转化为 rem 单位。

  1. npm i postcss-pxtorem

在项目根目录新建 postcss.config.js:

  1. // postcss.config.js
  2. // 用 vite 创建项目,配置 postcss 需要使用 post.config.js,之前使用的 .postcssrc.js 已经被抛弃
  3. // 具体配置可以去 postcss-pxtorem 仓库看看文档
  4. module.exports = {
  5. "plugins": [
  6. require("postcss-pxtorem")({
  7. rootValue: 37.5,
  8. propList: ['*'],
  9. selectorBlackList: ['.norem'] // 过滤掉.norem-开头的class,不进行rem转换
  10. })
  11. ]
  12. }

二次封装 axios

首先我们安装 npm i axios -S,在 src 目录下新建 utils 目录,并新建 axios.js 脚本:

  1. // src/utils/axios.js
  2. import axios from 'axios'
  3. import { Toast } from 'zarm'
  4. const MODE = import.meta.env.MODE // 环境变量
  5. axios.defaults.baseURL = MODE == 'development' ? '/api' : 'http://api.chennick.wang'
  6. axios.defaults.withCredentials = true
  7. axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
  8. axios.defaults.headers['Authorization'] = `${localStorage.getItem('token') || null}`
  9. axios.defaults.headers.post['Content-Type'] = 'application/json'
  10. axios.interceptors.response.use(res => {
  11. if (typeof res.data !== 'object') {
  12. Toast.show('服务端异常!')
  13. return Promise.reject(res)
  14. }
  15. if (res.data.code != 200) {
  16. if (res.data.msg) Toast.show(res.data.msg)
  17. if (res.data.code == 401) {
  18. window.location.href = '/login'
  19. }
  20. return Promise.reject(res.data)
  21. }
  22. return res.data
  23. })
  24. export default axios

最后我们将这个 axios 抛出,供页面组件请求使用。
在 utils 下新建一个 index.js,内容如下:

  1. import axios from './axios'
  2. export const get = axios.get
  3. export const post = axios.post

代理配置

打开 vite.config.js,添加如下代码:

  1. server: {
  2. proxy: {
  3. '/api': {
  4. // 当遇到 /api 路径时,将其转换成 target 的值
  5. target: 'http://api.chennick.wang/api/',
  6. changeOrigin: true,
  7. rewrite: path => path.replace(/^\/api/, '') // 将 /api 重写为空
  8. }
  9. }
  10. }

这样配置完之后,开发环境下,/api/userInfo -> http://api.chennick.wang/api/userInfo。这样就解决了大家老大难的跨域问题。

resolve.alias 别名设置

这里我们必须得设置好别名,否则在页面中,你会写出很长一串类似这样的代码 ../../../。
打开 vite.config.js,添加配置如下:

  1. ...
  2. import path from 'path'
  3. export default defineConfig({
  4. ...
  5. resolve: {
  6. alias: {
  7. '@': path.resolve(__dirname, 'src'), // src 路径
  8. 'utils': path.resolve(__dirname, 'src/utils') // src 路径
  9. }
  10. },
  11. })

总结

行文至此,我们的基础开发环境已经搭建完毕,涉及构建工具、前端框架、UI 组件库、HTTP 请求库、CSS 预加载器、跨域代理、移动端分辨率适配,这些知识都是一个合格的前端工程师应该具备的。