前言

Vite 进去好一段时间了,最开始反对 Vue,而当初曾经不受框架限度了。而 Vite 解决的是对于我的项目每次启动与打包构建等待时间长的问题,Vite 就是解决了该问题,进步开发效率与体验,本文作个简略的学习记录。

初始化

通过 Vite 官网命令行选项间接指定项目名称和想要应用的模板。例如,要构建一个 Vite + TypeScript 我的项目

# npm 6.xnpm init @vitejs/app vite-react-ts-antd-starter --template react-ts# npm 7+, 须要额定的双横线:npm init @vitejs/app vite-react-ts-antd-starter -- --template react-ts

创立完装置依赖后,运行我的项目如图:

配置路由

npm i react-router-dom@5.3.0

因为v6目前试用ts提醒等有一些问题,防止解说简单还是间接简略点用v5版本,用法不变。

首先新建三个页面文件,在 src/pages文件夹下新建三个页面

// homeconst Home = () => {  return <div>home page</div>}export default Home// aboutconst About = () => {  return <div>about page</div>}export default About// not foundconst NotFound = () => {  return <div>404 page</div>}export default NotFound

src/config目录下新建文件 routes.ts

import { lazy } from 'react'const Home = lazy(() => import('../pages/home'))const About = lazy(() => import('../pages/about'))const NotFound = lazy(() => import('../pages/not_found'))const routes = [  {    path:'/',    exact: true,    component: Home,    name:'Home'  },  {    path:'/home',    component: Home,    name:'Home'  },  {    path:'/about',    component: About,    name:'About'  },  {    path: '/404',    component: NotFound,  },]export default routes

新建文件src/router.tsx,路由文件入口

import { Suspense } from 'react'import { Route, Switch } from 'react-router-dom'import routes from './config/routes'const Router = () => {  const myRoutes = routes.map((item) => {    return <Route key={item.path} {...item} component={item.component} />  })  return (    <Suspense fallback={<div>Loading...</div>}>      <Switch>{myRoutes}</Switch>    </Suspense>  )}export default Router

App.tsx

import Router from './router'// 这里我封装了,其实就应用react-router-dom的Linkimport { Link } from './components' function App() {  return (    <div className="App">      <Link to="/">Home Page</Link>      <Link to="/about">About Page</Link>      <Router />    </div>  )}export default App

进入http://localhost:3000,此时就能够切换路由了

反对 Antd

在写该文章的时候,antd最新版本为4.18.1,应用vite打包会有谬误,而后回退到antd的4.17.1就能够了,具体见 https://github.com/ant-design...
 npm i antd@4.17.1 @ant-design/icons

在App.tsx引入antd的按钮组件:

import { Button } from 'antd'// ...<Button type="primary">按钮</Button>

antd应用的是less,这时还须要反对Less

npm i less less-loader -D

咱们还要对 antd 按需引入,装置插件

npm i vite-plugin-imp -D

vite.config.ts 的配置如下:

import { defineConfig } from 'vite'import react from '@vitejs/plugin-react'import vitePluginImp from 'vite-plugin-imp'// https://vitejs.dev/config/export default defineConfig({  plugins: [    react(),    vitePluginImp({      optimize: true,      libList: [        {          libName: 'antd',          libDirectory: 'es',          style: (name) => `antd/es/${name}/style`        }      ]    })  ],  css: {    preprocessorOptions: {      less: {        javascriptEnabled: true, // 反对内联 JavaScript      }    }  },})

此时查看页面,的确独自引入了按钮的款式组件

这样页面就失常显示出antd的按钮组件了

alias 别名设置

这个同webpack配置差不多,在 vite.config.js

import path from 'path'export default defineConfig({  resolve: {    alias: {      '@': path.resolve(__dirname, './src'),    }  }})

改一下 App.tsx 的 Link 组件引入,试验一下

- import { Link } from './components'+ import { Link } from '@/components'

此时编辑器会看到红色正告:Cannot find module '@/components' or its corresponding type declarations.,是因为咱们别名没有在 tsconfig.json 外面配置,批改:

"compilerOptions": {  "paths":{    "@/*": ["src/*"],   },}

eslint 与 Prettier 配置

npm i -D @typescript-eslint/parser eslint eslint-plugin-standard @typescript-eslint/parser @typescript-eslint/eslint-plugin                    

.eslintrc.js文件参考:

module.exports = {  extends: ['eslint:recommended', 'plugin:react/recommended'],  env: {    browser: true,    commonjs: true,    es6: true,  },  parser: '@typescript-eslint/parser',  parserOptions: {    ecmaFeatures: {      jsx: true,      modules: true,    },    sourceType: 'module',    ecmaVersion: 6,  },  plugins: ['react', 'standard', '@typescript-eslint'],  settings: {    'import/resolver': {      node: {        extensions: ['.tsx', '.ts', '.js', '.json'],      },      alias: [['@', './src']],    },  },  rules: {    semi: 0,    indent: 0,    'react/jsx-filename-extension': 0,    'react/prop-types': 0,    'react/jsx-props-no-spreading': 0,    'jsx-a11y/click-events-have-key-events': 0,    'jsx-a11y/no-static-element-interactions': 0,    'jsx-a11y/no-noninteractive-element-interactions': 0,    'jsx-a11y/anchor-is-valid': 0,    'no-use-before-define': 0,    'no-unused-vars': 0,    'implicit-arrow-linebreak': 0,    'consistent-return': 0,    'arrow-parens': 0,    'object-curly-newline': 0,    'operator-linebreak': 0,    'import/no-extraneous-dependencies': 0,    'import/extensions': 0,    'import/no-unresolved': 0,    'import/prefer-default-export': 0,    '@typescript-eslint/ban-ts-comment': 0,    '@typescript-eslint/no-var-requires': 0,  },}

Prettier 配置

npm i -D prettier

.prettierrc

{  "singleQuote": true,  "tabWidth": 2,  "endOfLine": "lf",  "trailingComma": "all",  "printWidth": 100,  "arrowParens": "avoid",  "semi": false,  "bracketSpacing": true}

环境变量

新增.env.env.prod文件,当应用自定义环境时变量要以VITE为前缀

.env                # 所有状况下都会加载.env.[mode]         # 只在指定模式下加载

.env

NODE_ENV=developmentVITE_APP_NAME=dev-name

.env.prod

NODE_ENV=productionVITE_APP_NAME=prod-name

获取环境变量

Vite在import.meta.env对象上裸露环境变量。批改 App.tsx,间接打印:

console.log('import.meta.env', import.meta.env)

重启运行 npm run dev

TS 提醒环境变量

在src目录下新建env.d.ts,接着按上面这样减少 ImportMetaEnv 的定义:

/// <reference types="vite/client" />interface ImportMetaEnv {  readonly VITE_APP_NAME: string  // 更多环境变量...}interface ImportMeta {  readonly env: ImportMetaEnv}

而后 import.meta.env.VITE_APP_NAME等这些自定义的环境变量就会有提醒了

结语

当初 Vite 官网尽管反对了 React,但对于 React 生态来说残缺的官网反对还有待欠缺,所以对于公司 webpack 我的项目开发环境迁徙 Vite 还是持激进态度,待 Vite 持续倒退,后续再缓缓跟进和学习再做降级。

本文我的项目地址:vite-react-ts-antd-starter

参考文章

  • Vite 2.0 + React + Ant Design 4.0 搭建开发环境