4

Preface

Vite has been out for a long time, and it started to support Vue, but now it is no longer restricted by the framework. Vite solves the problem of long waiting time for each project startup and packaging construction. Vite solves this problem and improves development efficiency and experience. This article is a simple learning record.

initialization

Directly specify the project name and template you want to use through the official Vite command line options. For example, to build a Vite + TypeScript project

# npm 6.x
npm 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

After creating the installation dependencies, run the project as shown in the figure:

image.png

Configure routing

npm i react-router-dom@5.3.0

Because v6 currently has some problems with ts prompts, etc., to avoid complicated explanations or simply use the v5 version, the usage remains the same.

First create three page files, create three pages under the src/pages folder

// home
const Home = () => {
  return <div>home page</div>
}

export default Home

// about
const About = () => {
  return <div>about page</div>
}

export default About

// not found
const NotFound = () => {
  return <div>404 page</div>
}

export default NotFound

Create a new file routes.ts in the src/config

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

Create a new file src/router.tsx , routing file entry

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的Link
import { 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

Enter http://localhost:3000 , then you can switch the route

image.png

Support Antd

At the time of writing this article, the latest version of antd is 4.18.1, and there will be errors when using vite to package, and then fall back to antd 4.17.1. For details, see https://github.com/ant-design/ ant-design/issues/33449
 npm i antd@4.17.1 @ant-design/icons

Introduce the button component of antd in App.tsx:

import { Button } from 'antd'

// ...
<Button type="primary">按钮</Button>

Antd uses less, and then it needs to support Less

npm i less less-loader -D

We also need to introduce antd and install plug-ins

npm i vite-plugin-imp -D

vite.config.ts is as follows:

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
      }
    }
  },
})

Looking at the page at this time, the button style component is indeed introduced separately

image.png

In this way, the page normally displays the button component of antd

image.png

alias alias setting

This is similar to the webpack configuration, in vite.config.js

import path from 'path'

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

Change the introduction of the Link component of App.tsx and try it

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

At this time, the editor will see a red warning: Cannot find module '@/components' or its corresponding type declarations. , because our alias is not configured in tsconfig.json, modify:

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

eslint and Prettier configuration

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

.eslintrc.js file reference:

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 configuration

npm i -D prettier

.prettierrc

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

Environment variable

Added .env and .env.prod files. When using a custom environment, variables should be prefixed VITE

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

.env

NODE_ENV=development
VITE_APP_NAME=dev-name

.env.prod

NODE_ENV=production
VITE_APP_NAME=prod-name

Get environment variables

Vite exposes environment variables on the import.meta.env Modify App.tsx and print directly:

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

Restart and run npm run dev

image.png

TS prompt environment variable

env.d.ts in the src directory, and then add the definition of ImportMetaEnv

/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_APP_NAME: string
  // 更多环境变量...
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

Then import.meta.env.VITE_APP_NAME and other custom environment variables will be prompted

Concluding remarks

Although Vite officially supports React, the complete official support for the React ecosystem has yet to be improved. Therefore, we still hold a conservative attitude towards the migration of the company's webpack project development environment to Vite. When Vite continues to develop, we will slowly follow up and learn later. Do an upgrade.

The project address of this article: vite-react-ts-antd-starter

Reference article


JackySummer
535 声望238 粉丝