preface

Vite has been around for a while, originally supporting Vue, but now it’s framework free. Vite solves the problem of long waiting time for each project startup and package construction. Vite solves the problem and improves development efficiency and experience. This article makes a simple learning record.

Initialize the

Specify the project name and the template you want to use directly from the official Vite command line options. For example, 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-tsCopy the code

After the installation dependency is created, run the project as shown:

Configure the routing

NPM I [email protected]Copy the code

V6 as a result of the current trial TS tips, there are some problems, to avoid explaining complex or direct simple point with V5 version, usage unchanged.

Start by creating three new page files, and create three new pages in 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
Copy the code

Create the routes. Ts file in the SRC /config directory

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
Copy the code

Create a file SRC /router. TSX and route the 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
Copy the code

App.tsx

import Router from './router'
// Use the 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
Copy the code

Go to http://localhost:3000 and switch routes

Support Antd

At the time of writing, the latest antD version is 4.18.1. There are errors in using vite packaging, and then revert to ANTD’s 4.17.1. For details, see github.com/ant-design/…

NPM [email protected] @ I ant - design/ICONSCopy the code

Introducing antD button components in app.tsx:

import { Button } from 'antd'

// ...
<Button type="primary"> Button < / Button >Copy the code

Antd uses LESS, so you need to support less

npm i less less-loader -D
Copy the code

We also need to introduce and install plug-ins for ANTD on demand

npm i vite-plugin-imp -D
Copy the code

The configuration of 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.// Support inline JavaScript}}}})Copy the code

Viewing the page at this point does introduce the style component of the button in its own right

The page now displays the button component of ANTD normally

Alias Alias Settings

This is similar to the Webpack configuration in viet.config.js

import path from 'path'

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

Change the Link component in app.tsx to try it out

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

Corresponding type declarations: Cannot find module ‘@/components’ or its corresponding type declarations.

"compilerOptions": {
  "paths": {"@ / *": ["src/*",}}Copy the code

Eslint is configured with Prettier

npm i -D @typescript-eslint/parser eslint eslint-plugin-standard @typescript-eslint/parser @typescript-eslint/eslint-plugin                    
Copy the code

.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: [[The '@'.'./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,}}Copy the code

Prettier configuration

npm i -D prettier
Copy the code

.prettierrc

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

The environment variable

New. Env,.env.prod files. Variables should be prefixed with VITE when using custom environment

.env.[mode] # load only in specified modeCopy the code

.env

NODE_ENV=development
VITE_APP_NAME=dev-name
Copy the code

.env.prod

NODE_ENV=production
VITE_APP_NAME=prod-name
Copy the code

Getting environment variables

Vite exposes environment variables on the import.meta.env object. Modify app.tsx to print directly:

console.log('import.meta.env'.import.meta.env)
Copy the code

Restart and run NPM run dev

TS indicates environment variables

Create env.d.ts in the SRC directory and add the ImportMetaEnv definition as follows:

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

interface ImportMetaEnv {
  readonly VITE_APP_NAME: string
  // More environment variables...
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
Copy the code

Then custom environment variables such as import.meta.env.vite_app_name will be prompted

conclusion

Although React is officially supported by Vite, the complete official support for React ecosystem still needs to be improved. Therefore, the company still holds a conservative attitude towards migrating Vite to the development environment of Webpack project. After Vite continues to develop, we will gradually follow up and learn and then upgrade it.

The project address: Viet-React-TS-ANTD-starter

Refer to the article

  • Vite 2.0 + React + Ant Design 4.0