preface

What is vite 😳? It’s 2021. You don’t know, do you? If you don’t know be careful you don’t want to use vUE.

Vite is a development and construction tool. In the development process, it uses the browser native ES Module feature to import organizational code, and in production, it uses Rollup as a packaging tool, and especially vUE author Yu Xi organized team development, it has the following characteristics:

  • Start the fast
  • Hot Module Update
  • According to the need to compile
  • Perfect compatibilityrollupecological

Our new project has tried to use Vite, the effect is really better than Webpack, now I will explain how to build an enterprise vite engineering.

Basis of preparation

  1. New Folderconfig.public.src
  2. generatepackage.jsonRun the following command 👇
$ npm init
Copy the code
  1. newindex.html.tsconfig.json.vite.config.ts..gitignorefile

The project infrastructure is as follows:

├ ─ ─ the configConfig file for project scaffolding├ ─ ─ the public# static file├ ─ ─ the SRC# source code├ ─ ─ index. HTML# root├ ─ ─ gitignoreGit ignores files├ ─ ─ vite. Config. TsProject global Vite configuration file├ ─ ─ tsconfig. JsonProject global TS configuration file└ ─ ─ package. Json# package.json
Copy the code

start

Installation must depend on

The development of

$ npm install vite typescript @vitejs/plugin-react-refresh -D
Copy the code

production

$ npm install react react-dom -S
Copy the code

Write the configuration

Create main. TSX,app. TSX,app.css in the SRC folder

  1. insrc/App.tsxThe following code is written in the file
import React, { FC, useEffect } from 'react';
import './app.css';
const App: FC = () = > {
  useEffect(() = > {
      console.log(`vite-react-cil`); } []);return (
    <div>
      <h2>Welcome to vite-react-cil</h2>
    </div>
  );
};

export default App;
Copy the code
  1. insrc/app.cssThe following code is written in the file
* {
  padding: 0;
  margin: 0;
}
.App{
  width:200px;
}
Copy the code
  1. insrc/main.tsxThe following code is written in the file
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>.document.getElementById('root'));Copy the code
  1. intsconfig.jsonThe following code is written in the file
{
  "compilerOptions": {
    "baseUrl": ". /"."paths": {
      "@ / *": ["src/*"]},"types": ["vite/client"]."target": "ESNext"."useDefineForClassFields": true."lib": ["DOM"."DOM.Iterable"."ESNext"]."allowJs": false."skipLibCheck": false."esModuleInterop": true."allowSyntheticDefaultImports": true."strict": true."forceConsistentCasingInFileNames": true."module": "ESNext"."moduleResolution": "Node"."resolveJsonModule": true."isolatedModules": true."noEmit": true."jsx": "react"
  },
  "include": ["./src"]."exclude": ["node_modules"]}Copy the code
  1. inconfigNew folderpluginsFolder, this article is specially used for processingviteThird party plugins then inconfig/pluginsNew folderindex.tsFile, and inindex.tsWrite the following code in the file:
import { Plugin } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
export default function createVitePlugins() {
  const vitePlugins: (Plugin | Plugin[])[] = [
    reactRefresh(),
  ];
  return vitePlugins;
}
Copy the code
  1. invite.config.tsThe following code is written in the file
import { defineConfig } from 'vite';
import createVitePlugins from './config/plugins';
export default defineConfig((configEnv) = > {
  return {
    plugins: createVitePlugins(),
  };
});
Copy the code
  1. Store a favicon.ico diagram file in the public folder.

  2. Write the following code in the index.html file

<! DOCTYPEhtml>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
    <title>vite-react-cil</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

Copy the code
  1. in.gitignoreThe following configuration is recorded in the file
node_modules
.DS_Store
dist
coverage
dist-ssr
*.local
Copy the code
  1. inpackage.jsonAdd the following code to the file
{
  "scripts": {
    "dev": "vite"}},Copy the code

Run the project

We can run the project with the following command:

$ npm run dev
Copy the code

The appearance of the above image indicates that the project has been successfully started. At this point, a simplified version of the scaffolding is complete.

extension

css-module/less/scss

Vite supports modules by default. Just add a module to the file name, such as xx.module. CSS.

SCSS/LESS support, installation dependencies, as follows:

$ npm install less sass -D
Copy the code

CSS/less mode of the module as well as CSS, such as: xx. The module. The SCSS, xx. The module. The less

Add the global less/ SCSS variable as follows 👇 :

  1. insrcAdd to folderassetsFolder, and addingscssFolder, inscssAdd to foldervarible.scssFile, and insrc/assets/scss/varible.scssTo write the following code:
$bg: #f0f0f0;
@mixin flexContainer($jc) {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: $jc;
}
@mixin style($size, $color, $bold: normal) {
  font-size: $size;
  color: $color;
  font-weight: $bold;
}
Copy the code
  1. inconfigUnder the folder, addstyleFolder, and instyleAdd to folderindex.ts.config/style/index.tsTo write the following code:
import { CSSOptions } from 'vite';
const cssOption: CSSOptions = {
  preprocessorOptions: {
    less: {
      javascriptEnabled: true,},scss: {
      additionalData: '@import "./src/assets/scss/varible.scss"; ',}}};export default cssOption;
Copy the code

Note:

AdditionalData must be followed by @import; Otherwise, an error will be reported

  1. findvite.config.tsFile, and add the following code:
import { defineConfig } from 'vite';
import createVitePlugins from './config/plugins';
+ import cssOption from './config/style';
export default defineConfig((configEnv) = > {
  return {
    plugins: createVitePlugins(),
    + css: cssOption,
  };
});
Copy the code
  1. willsrc/app.cssIn theapp.cssSwitch toapp.module.scss, such as:app.css->app.module.scss.

Change the code in the SRC/app.tsx file:

import React, { FC, useEffect } from 'react';
 - import './app.css';
 + import styles from './app.module.scss';
const App: FC = () = > {
  useEffect(() = > {
      console.log(`vite-react-cil`); } []);return (
    <div className={styles.App}>
      <h2>Welcome to vite-react-cil</h2>
    </div>
  );
};

Copy the code

The environment variable

In vue cil,create-react-app, you can use cross-env+. Env to set custom environment variables, and process.env to set custom environment variables, but vite is a little different.

  • viteIn theSet up theThe environment variable
  1. new.env..env.alpha..env.preprod..env.prodFour files, moresrcPeer directory.

Env file write the following code:

NODE_ENV=development
VITE_APP_ANT=dev
Copy the code

Env.alpha file write the following code:

NODE_ENV=production
VITE_APP_ANT=alpha
Copy the code

Env. Preprod file write the following code:

NODE_ENV=production
VITE_APP_ANT=preprod
Copy the code

Env. Prod file write the following code:

NODE_ENV=production
VITE_APP_ANT=prod
Copy the code

They represent four environment variables: development, test, pre-release, production, and if you want to extend the other variables, and so on.

Note:

Custom environment variables are only exposed to VITE if they are prefixed by VITE, such as VITE_APP_SOME

  1. findpackage.jsonFile, add the following code:
{
  "scripts": {-"dev": "vite",
   + "dev": "vite --mode dev",
   + "build:alpha": "vite build --mode alpha",
   + "build:preprod": "vite build --mode preprod",
   + "build:prod": "vite build --mode prod"}},Copy the code

Tip:

The reason for adding –mode to the package.json command is to override the default production,development mode used by the command

  1. typescriptDeclare custom environment variables under the environment.

In the SRC folder, create a new file named viet-env.d. ts, SRC/viet-env.d. ts and write the following code:

/// <reference types="vite/client" />
interface ImportMetaEnv {
  VITE_APP_ANT: 'dev' | 'alpha' | 'preprod' | 'prod';
}
Copy the code
  • viteIn theTo obtainThe environment variable

Env is not process.env. If you want to use import.meta. Env every time in your code, it would be too complicated to write.

SRC /utils/index.ts SRC /utils/index.ts SRC /utils/index.ts

export const environmentVariable = () = > {
  const env = import.meta.env.VITE_APP_ANT;
  let parps = null;
  switch (env) {
    case 'dev': 
      parps = 'dev';
      break;
    case 'alpha': 
      parps = 'alpha';
      break;
    case 'preprod':
      parps = 'preprod';
      break;
    case 'prod': 
      parps = 'prod';
      break;
    default:
      parps = 'dev';
      break;
  }
  return parps;
};
Copy the code

So, regardless of where we want to use the environmentVariable, we can just call the environmentVariable method.

The base/server configuration

  1. inconfigNew folderindex.tsIn theconfig/index.tsTo write the following code:
/ * * *@description Development port */
export const VITE_APP_PORT = 3000;
/ * * *@description Common base path */
export const VITE_APP_BASE = '/';
/ * * *@description Whether to automatically open the application in the browser */
export const VITE_APP_OPEN = true;
Copy the code

Note:

Env: import. Meta. Env: import from config file: import. I have to write it as a function

  1. inconfigNew foldersetupProxy.tsFile for custom proxy,config/setupProxy.tsTo write the following code:
import { ProxyOptions } from 'vite';
const proxy: Record<string.string | ProxyOptions> = {
  // Short for string
  '/foo': 'http://localhost:4567'.// This is an option
  '/api': {
    target: 'http://jsonplaceholder.typicode.com'.changeOrigin: true.rewrite: (path) = > path.replace(/^\/api/.' '),
    / / more please see: https://cn.vitejs.dev/config/#server-proxy}};export default proxy;
Copy the code
  1. findvite.config.tsFile, and add the following code:
import { defineConfig } from 'vite';
import createVitePlugins from './config/plugins';
import cssOption from './config/style';
+ import { VITE_APP_BASE, VITE_APP_PORT, VITE_APP_OPEN } from './config';
+ import proxy from './config/setupProxy';
export default defineConfig((configEnv) = > {
  return {
    + base: VITE_APP_BASE,
    plugins: createVitePlugins(),
    css: cssOption,
    + server: {
      host: true.port: VITE_APP_PORT,
      open: VITE_APP_OPEN,
      proxy,
    },
  };
});
Copy the code

The alias configuration

Go to the vite.config.ts file and add the following code:

First installation path.

$ npm install path -D
Copy the code
... 省略
+ import path from 'path';
export default defineConfig((configEnv) = > {
  return{... Omit + resolve: {alias: {
        The '@': path.resolve(__dirname, 'src'),}}}; });Copy the code

The build configuration

  1. findconfig/index.tsFile, add the following code:
. omit/ * * *@description Whether to enable packaging analysis visualization in the packaging environment */
+ export const VITE_APP_VISUALIZER = false;
/ * * *@description Whether to remove console.log */ in a packaged environment
+ export const VITE_APP_CONSOLE = true;
/ * * *@description In the package environment, remove the debugger */
+ export const VITE_APP_DEBUGGER = true;
/ * * *@description Whether to generate the source map file */ in the packaging environment
+ export const VITE_APP_SOURCEMAP = false;
Copy the code
  1. inconfig/pluginsIn the folder, create avisualizer.tsfile

Install a rollup – plugin – visualizer

$ npm install rollup-plugin-visualizer -D
Copy the code

In the config/plugins/visualizer. Ts file, write the following code:

import visualizer from 'rollup-plugin-visualizer';
export default function configVisualizerConfig() {
  return visualizer({
   // Write the packaged dependency analysis visualization page to node_modules so it doesn't take up space
    filename: './node_modules/.cache/visualizer/stats.html'.open: true.gzipSize: true.brotliSize: true}); }Copy the code
  1. findconfig/plugins/index.tsFile, add the following code:
import { Plugin } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
+ import { VITE_APP_VISUALIZER } from '.. /index';
+ import configVisualizerConfig from './visualizer';
export default function createVitePlugins() {
  const vitePlugins: (Plugin | Plugin[])[] = [
    reactRefresh(),
  ];
  + VITE_APP_VISUALIZER && vitePlugins.push(configVisualizerConfig());
  return vitePlugins;
}
Copy the code
  1. inconfigUnder the folder, create a folderbuild.tsFile, and write the following code:
import { BuildOptions } from 'vite';
import { VITE_APP_CONSOLE, VITE_APP_DEBUGGER, VITE_APP_SOURCEMAP } from '.. /config';
const build: BuildOptions = {
  terserOptions: {
    compress: {
      keep_infinity: true.drop_console: VITE_APP_CONSOLE,
      drop_debugger: VITE_APP_DEBUGGER,
    },
  },
  outDir: 'dist'.// Specify the output path directory
  assetsDir: 'assets'.// Specify the directory where static resources are generated for packaging
  sourcemap: VITE_APP_SOURCEMAP, // Whether to generate the source map file after the build
};
export default build;
Copy the code
  1. findvite.config.tsFile, add the following code:
... 省略
+ import build from './config/build';
export default defineConfig((configEnv) = > {
  return {
   ... 省略
    + build
  };
});
Copy the code

The advanced

eslint

  1. Install the following dependencies first:
$ npm install @typescript-eslint/eslint-plugin eslint eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier  @typescript-eslint/parser eslint-config-prettier eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-simple-import-sort -DCopy the code

Tip:

Install the @typescript-eslint/eslint-plugin,eslint-plugin-react,eslint-plugin-react-hooks dependencies on the plugin-react-hooks. Some important, recommended installation.

  1. new.eslintrc.js..eslintignoreTwo files, moresrcPeer directory.

The.eslintrc.js file writes the following code:

module.exports = {
  root: true.parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaVersion: 2020.sourceType: 'module'.ecmaFeatures: {
      jsx: true,}},settings: {
    react: {
      version: 'detect',}},env: {
    browser: true.amd: true.node: true,},extends: [
    'eslint:recommended'.'plugin:react/recommended'.'plugin:react-hooks/recommended'.'plugin:jsx-a11y/recommended'.'plugin:prettier/recommended',].plugins: ['simple-import-sort'.'prettier'].rules: {
    'prettier/prettier': ['error', {}, { usePrettierrc: true}].'react/react-in-jsx-scope': 'off'.'jsx-a11y/accessible-emoji': 'off'.'react/prop-types': 'off'.'@typescript-eslint/explicit-function-return-type': 'off'.'simple-import-sort/imports': 'off'.'simple-import-sort/exports': 'error'.'jsx-a11y/anchor-is-valid': [
      'error',
      {
        components: ['Link'].specialLink: ['hrefLeft'.'hrefRight'].aspects: ['invalidHref'.'preferButton'],},],'no-debugger': 0.eqeqeq: 2.'default-case': 1.'no-empty-function': 1.'no-multi-spaces': 1.'spaced-comment': ['error'.'always'].'no-multiple-empty-lines': ['error', { max: 3}],}};Copy the code

Tip:

Eslint configuration: EsLint configuration: esLint configuration: esLint configuration: ESLint configuration: ESLint configuration: ESLint configuration

The.eslintignore file writes the following code:

node_modules
.DS_Store
dist
coverage
src/__tests__
__tests__
dist-ssr
*.local
node_modules/*
Copy the code
  1. findpackage.jsonFile, add the following code:
... 省略
+ "lint": "eslint ./src --ext .jsx,.js,.ts,.tsx",
+ "lint:fix": "eslint ./src --ext .jsx,.js,.ts,.tsx --fix".Copy the code

The NPM run lint command can detect all improper code in SRC files.

NPM run lint: the fix command automatically fixes all non-canonical code in SRC files.

😦, now we can actually detect code specifications, but there is one problem, the detected code must be typed by me, and it is not automatically detected in development mode, this behavior is very unfriendly, like webpack we can use eslint-Loader to detect code in development mode, Does vite have plugins like eslint-Loader? B: of course.

  1. Install the following dependencies:
$ npm install vite-plugin-checker -D
Copy the code
  1. findconfig/index.tsFile, add the following code:
/ * * *@description Whether to enable ESLint */ in development mode
+ export const VITE_APP_ESLINT = true;
Copy the code
  1. findconfig/pluginsFolder, neweslint.tsFile, and inconfig/plugins/eslint.tsWrite the following code in the file:
import checker from 'vite-plugin-checker';
export default function configEslint() {
  return [
    checker({
      typescript: true.eslint: {
        files: ['./src'].extensions: ['.ts'.'.tsx'.'.jsx',}})]; }Copy the code

Tip:

I don’t recommend using the viet-plugin-esLint plugin, which prevents hot updates when detecting errors.

  1. findconfig/plugins/index.tsFile, add the following code:
import { Plugin } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
+ import { VITE_APP_VISUALIZER,VITE_APP_ESLINT } from '.. /index';
import configVisualizerConfig from './visualizer';
+ import configEslint from './eslint';
export default function createVitePlugins() {
    constvitePlugins: (Plugin | Plugin[])[] = [ reactRefresh(), ]; VITE_APP_VISUALIZER && vitePlugins.push(configVisualizerConfig()); + VITE_APP_ESLINT && vitePlugins.push(... configEslint());return vitePlugins;
}
Copy the code

At this point, we have configured a configuration for automatic detection in a development environment.

jest

  1. Install the following dependencies:
$ npm install @testing-library/jest-dom @types/jest jest ts-jest identity-obj-proxy -D
Copy the code
  1. newjest.config.jsFile, withsrcLevel, and write the following code:
module.exports = {
  preset: 'ts-jest'.roots: ['<rootDir>/src'].moduleDirectories: ['node_modules'.'src'].transform: {
    '^.+\\.tsx$': 'ts-jest'.'^.+\\.ts$': 'ts-jest',},testRegex: '(/__tests__/.*.(test|spec)).(jsx? |tsx?) $'.moduleFileExtensions: ['ts'.'tsx'.'js'.'jsx'.'json'.'node'].collectCoverage: true.collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx,js,jsx}'].coverageDirectory: '<rootDir>/coverage/'.verbose: true.testTimeout: 30000.testEnvironment: 'jsdom'.coveragePathIgnorePatterns: ['<rootDir>/node_modules/'.'(.*).d.ts$'].moduleNameMapper: {
    '^.+\\.module\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg)$': 'identity-obj-proxy',}};Copy the code

Tip:

Each company’s jEST configuration is different, so it may not follow my configuration. For jEST configuration, please refer to jEST official website

  1. insrcUnder the folder, add__tests__Folder, and in__tests__Folder is being addedApp.test.tsxFile, and write the following code:
import React from 'react';
import { render, cleanup, getByTestId } from '@testing-library/react';
import '@testing-library/jest-dom';
import App from '.. /App';

afterEach(cleanup);

describe('<App />'.() = > {
  it('renders without errors'.() = > {
    const { container } = render(<App />);
    // The a tag contains data-testid='aNoDisabled' to check
    expect(getByTestId(container, 'aNoDisabled')).not.toBeDisabled();
  });
});
Copy the code

Tip:

Everyone’s test style is different, you can have their own test style to test, you can write different tests according to, component, module, method and so on, I will introduce a simple test

4. Find the package.json file and add the following code:

... 省略
+  "test": "jest --colors --passWithNoTests",
+  "test:watch": "jest --watchAll"
Copy the code

Tip:

If you find it difficult to configure jEST on your own, you can recommend the use of viet-plugin-test

SVG is imported by name

If we want to import multiple SVG files, the usual approach is to import xx from ‘xx.svg, so that we can write multiple imports, either by requiring an array list in JS, or by directly retrieving all SVG files in the folder, and then iterating through them. Most of these schemes are too cumbersome.

Webpack can use the SVG sprite-loader plugin to reduce our operations, directly write the SVG name can be directly imported, very convenient.

This is also possible in Vite, via the vite-plugin-SVG-icons plugin, which is as follows:

  1. Install dependencies
$ npm install vite-plugin-svg-icons -D
Copy the code
  1. insrcUnder the folder, create a foldericonsFolder, and iniconsIn the folder, add onelogon.svgFile.
  2. pluginsUnder the folder, create a foldersvgIcons.tsFile, write the following code:
import viteSvgIcons from 'vite-plugin-svg-icons';
import path from 'path';
export default function configSvgIcons() {
 return viteSvgIcons({
   iconDirs: [path.resolve(process.cwd(), 'src/icons')].symbolId: 'icon-[dir]-[name]'}); }Copy the code
  1. inconfig/plugins/index.tsAdd the following code:
+ import configSvgIcons from './svgIcons';
import { Plugin } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
export default function createVitePlugins() {
 constvitePlugins: (Plugin | Plugin[])[] = [ reactRefresh(), + configSvgIcons() ]; . omitreturn vitePlugins;
}
Copy the code

5 In the SRC folder, create the Components folder, create the svgIcon folder, and create the index. TSX folder in the SRC/Components /svgIcon folder and write the following code:

import React, { memo, useMemo } from 'react';
export type svgProps = {
  iconClass: string; fill? : string; fontSize? : string; className? : string; style? : React.CSSProperties; onClick? : React.MouseEventHandler<SVGSVGElement>; };const SvgIcon: React.FC<svgProps> = memo(function SvgIcon({
  iconClass,
  fill,
  fontSize = '18px',
  className,
  onClick,
  style,
}) {
  const iconName = useMemo(() = > '#icon-' + iconClass, [iconClass]);
  return (
    <svg
      fontSize={fontSize! }
      style={{ . svgStyle.fontSize.. style }}
      aria-hidden="true"
      className={className! }
      onClick={onClick}
    >
      <use xlinkHref={iconName} fill={fill! } />
    </svg>
  );
});
const svgStyle = {
  width: '1em'.height: '1em'.verticalAlign: '-0.15em'.overflow: 'hidden'.fill: 'currentColor'.fontSize: '1.1 em'};export default SvgIcon;
Copy the code

6 Add the following code to the SRC /main. TSX file:

+ import 'virtual:svg-icons-register'; . omitCopy the code
  1. Used in thesrc/App.tsxAdd the following code to the file:
. Omit +import SvgComponent from './components/svgIcon';
const App: FC = () = > {
  return (
    <div className={styles.App}>
      <h2>Welcome to vite-react-cil</h2>
     + <SvgComponent iconClass="logon" fontSize="30px" />
    </div>
  );
};
export default App;
Copy the code

Third-party UI components can be imported on demand

In the project, ANTD, Element and other UI components may be used. We generally introduce them as needed, not all of them, which will cause a large package when packaging. The specific operation of Vite is as follows:

  1. Install dependencies
$ npm install vite-plugin-style-import -D
Copy the code
$ npm install antd -S
Copy the code
  1. inconfig/pluginsUnder the folder, create a folderstyleImport.tsFile, write the following code:
import styleImport from 'vite-plugin-style-import';
export default function configStyleImport() {
  return styleImport({
    libs: [{libraryName: 'antd'.esModule: true.resolveStyle: (name) = > {
          return `antd/es/${name}/style/index`; }},]}); }Copy the code
  1. inconfig/plugins/index.tsAdd the following code:
+ import configStyleImport from './styleImport';
import { Plugin } from 'vite';
import reactRefresh from '@vitejs/plugin-react-refresh';
export default function createVitePlugins() {
  constVitePlugins: (Plugin | plugins) [] [] = [reactRefresh (),... omitted + configStyleImport ()]; . omitreturn vitePlugins;
}
Copy the code

Prettierrc Formatting code

Install the following dependencies:

$ npm install prettier -D
Copy the code

Prettier-code Formatter used when vscode editor prettier-code Formatter is installed

  1. new.prettierignore..prettierrcThese two files, moresrcAt the same directory

.prettierrc writes the following code:

{
  "singleQuote": true."trailingComma": "all"."prettier.tabWidth": 2."editor.defaultFormatter": "esbenp.prettier-vscode"."[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[css]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[scss]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "overrides": [{"files": ".prettierrc"."options": { "parser": "json"}}}]Copy the code

Tip:

The configuration file for Prettierrc can also be a JS file for prettierrc, for example, see the official website for prettierrc

.prettierIgnore Write the following code:

**/*.md
**/*.svg
**/*.ejs
**/*.html
package.json
Copy the code
  1. inpackage.jsonAdd the following code to:
{
  "scripts": {
    "format": "prettier --loglevel warn --write \"./**/*.{js,jsx,ts,tsx,css,md,json}\"",}}Copy the code

Enter NPM run format to format the code

mock

The plugin-vite plugin is recommended. The configuration of the plugin-vite plugin is similar to that of the plugin-vite plugin. In config/plugins, create configMock.ts and create a mock folder. The mock folder is the same level as the SRC directory.

editorconfig

The team code style is unified and editorConfig is recommended.

  1. vscodeEditor install plug-inEditorConfig for VS CodeOf course, other editors can also be used, just need to click the correspondingeditorconfigPlugins, I’ll do it herevscodeGive priority to.
  2. new.editorconfigFile, withsrcThe same directory, write the following code:
[*.{js,jsx,ts,tsx,vue}] charset = utf-8 indent_style = space indent_size = 2 end_of_line = lf trim_trailing_whitespace =  true insert_final_newline = true max_line_length = 100Copy the code

Tip:

Each team’s code style configuration is not consistent and needs to be configured according to the actual situation of their own team

The deployment of

Every company has different deployments, some use Jenkins, GH-Pages, Docker, etc., so you can read other articles on deployment, I won’t go into it here.

conclusion

After the previous step by step construction, the final overall structure of the project is as follows:

├ ─ ─ the config │ ├ ─ ─ the plugins │ ├ ─ ─ style │ ├ ─ ─ build. Ts │ ├ ─ ─ but ts │ ├ ─ ─ setupProxy. Ts ├ ─ ─ public ├ ─ ─ the mock ├ ─ ─ the SRC │ ├ ─ ─ __tests__ │ ├ ─ ─ assets │ ├ ─ ─ components │ ├ ─ ─ the ICONS │ ├ ─ ─ utils │ ├ ─ ─ app. The module. The SCSS │ ├ ─ ─ app. The TSX │ ├ ─ ─ main. The TSX │ ├ ─ ─ vite - env. Which s ├ ─ ─ the editorconfig ├ ─ ─ the env ├ ─ ─ the env. The alpha ├ ─ ─ the env. Preprod ├ ─ ─ the env. Prod ├ ─ ─ the eslintignore ├ ─ ─ . Eslintrc. Js ├ ─ ─. Gitignore ├ ─ ─ the prettierignore ├ ─ ─ the prettierrc ├ ─ ─ jest. Config. Js ├ ─ ─ index. The HTML ├ ─ ─ tsconfig. Json ├ ─ ─ Vite. Config. Ts └ ─ ─ package. The jsonCopy the code

Conclusion:

  • viteAlthough it is a new show, but the disadvantages are also very obvious, ecology has not been completely popularized, it is stillwebpackDominant, build the advantage.
  • viteIn terms of performancewebpackOkay, and becauseviteNow many people know whyrollupAnyway,viteAre worth learning and understanding.
  • We can not blindly follow the wind, see other people’s company usevite, I also want to re-constitute the company’s projectsviteFor more practical reasons.

Project address/case study

The project address is 👉 viet-react-cil.

Case study:

  • ant-simple-proIt’s a supportvue3.react.angularThree big framework mid-platform solutions,3.0Edition is fully usedviteRefactoring.
  • JoL-playerIt’s a powerful onereactPlayer,typescriptThe development,bate3.0Version withviterefactoring

encourage

This article, is the author in 10.1 in the meantime to write, although not very tall is still the article, but also attentively wrote, also hope you little friends, encourage 👍, so I will be more dynamic 💪.