Build front-end project 5 from scratch (optimization of Viet.config. ts)

Build a lean front-end project step by step from scratch.

Vue3.0 + Vite + TypeScript + Element Plus + Vue Router + AXIos + Pinia

Canonicalization: Eslint + Airbnb JavaScript Style + husky + Lint-staged

Package management: YARN

Historical content

Building front-end Project 1 from Scratch (Vue3+Vite+TS+Eslint+Airbnb+ Prettier)

Build Front-end Projects FROM Scratch HusKY + Lint-Staged

Build front-end project 3 (Element Plus) from scratch

Build front-end project 4 (Vue Router) from scratch

This chapter content

Optimizes the viet.config. ts configuration in your project, automatically introduces apis, components as needed, starts optimizations, listens for configuration file changes and reloads pages.

Automatic import on demand

Fixed issue: Additional import of vue API is required every time vue, VUe-Router, pinia is used. For example, to use ref, import {ref} from ‘vue’ first.

The use effect is as follows:

The installation

Install dependencies. The following two libraries were installed in Part 3.

yarn add unplugin-vue-components unplugin-auto-import --dev
Copy the code

configuration

Configuration vite. Config. Ts

// vite.config.ts import AutoImport from 'unplugin-auto-import/vite'; import Components from 'unplugin-vue-components/vite'; Export default {plugins: [AutoImport({imports: ['vue', 'vue-router', 'pinia'], // ++ // [ElementPlusResolver()],}), Components({// dirs specifies the location of the component, default SRC/Components // allows us to use our own Components without the trouble of importing dirs: [' SRC /components/'], // ++ / Resolvers: [ElementPlusResolver()],},],}Copy the code

TypeScript error

TypeScript error: the name “ElMessage” cannot be found, i.e., the component name cannot be found. This is because auto-imports. D. ts and components. D. ts files are generated in the project root directory by default, and normal TypeScript parsed files are stored in the SRC folder. So we move the two files to the SRC folder and specify the address of the above files in viet.config. ts.

// vite.config.ts
export default {
  plugins: [
    AutoImport({
      dts: './src/auto-imports.d.ts',                 // ++
    }),
    Components({
      dts: './src/components.d.ts',                   // ++
    }),
  ],
}
Copy the code

Eslint error

Eslint error: ‘useRouter’ is not defined. That is, the incoming API cannot be found. Because Eslint doesn’t know about the apis we’ve introduced on demand. So it needs to be configured in and in vite.config.ts and.eslintrc.js.

// vite.config.ts
export default {
  plugins: [
    AutoImport({
      // Generate corresponding .eslintrc-auto-import.json file.
      // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
      eslintrc: {
        enabled: true, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
    }),
  ],
}
Copy the code

The above configuration generates an.eslintrc-auto-import.json file in the root directory with all the API names we introduced.

Load the file in.eslintrc.js.

// .eslintrc.js
module.exports = { 
  extends: [
    // ...
    './.eslintrc-auto-import.json',            // ++
  ],
}
Copy the code

Start project, no error reported.

Start the optimization

When we develop projects using Vite, we often see the following on the command line when we first start up:

new dependencies found: vue updating…

This can take a long time, and there are plug-ins to solve this problem.

The installation

Install dependencies

yarn add vite-plugin-optimize-persist vite-plugin-package-config --dev
Copy the code

configuration

Configuration vite. Config. Ts

// vite.config.ts
import OptimizationPersist from 'vite-plugin-optimize-persist'  // ++
import PkgConfig from 'vite-plugin-package-config'              // ++

export default {
  plugins: [
    // ...
    PkgConfig(),                                 // ++
    OptimizationPersist()                        // ++
  ],
}
Copy the code

Once configured, the first time we use on-demand import, it will generate content in package.json (depending on what components your project is using), allowing you to quickly start the project again.

Refactoring vite. Config. Ts

At this point, the content in viet.config. ts was getting more and more, so we extracted the plugins from the file and put them in a separate file. Create the config folder under the root directory.

Where constant. Ts puts some constants, vitePlugins. Ts puts plugins used by Vite. You can also use separate files for each of your plugins, depending on the number of plugins you use for your project.

Rearrange the plugins used previously as follows:

// vitePlugins.ts import type { Plugin } from 'vite'; import vue from '@vitejs/plugin-vue'; import AutoImport from 'unplugin-auto-import/vite'; import Components from 'unplugin-vue-components/vite'; import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'; import VueSetupExtend from 'vite-plugin-vue-setup-extend'; import OptimizationPersist from 'vite-plugin-optimize-persist'; import PkgConfig from 'vite-plugin-package-config'; import { ConfigEnv } from 'vite'; export default (env: ConfigEnv) => { const vitePlugins: (Plugin | Plugin[])[] = [ vue({ include: [/.vue$/], }), AutoImport({ dts: './src/auto-imports.d.ts', imports: ['vue', 'vue-router'], // Generate corresponding .eslintrc-auto-import.json file. // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals eslintrc: { enabled: true, // Default `false` filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json` globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable') }, resolvers: [ElementPlusResolver()], }), Components({ dts: './src/components.d.ts', extensions: ['vue'], include: [/.vue$/, /.vue? Vue /], // imports specifies the location of the component. SRC /components is used by default. [ElementPlusResolver({ importStyle: 'sass' })], }), VueSetupExtend(), PkgConfig(), OptimizationPersist(), ]; return vitePlugins; };Copy the code

The configuration is in vite.config.ts

import { defineConfig, loadEnv, ConfigEnv } from 'vite';
import { resolve } from 'path';
import vitePlugins from './config/vitePlugins';    // ++

import {
  VITE_PORT,
  VITE_DROP_CONSOLE,
  API_BASE_URL,
  API_TARGET_URL,
} from './config/constant';

export default defineConfig((env: ConfigEnv) => {
  const viteEnv = loadEnv(env.mode, `.env.${env.mode}`);
  return {
    base: viteEnv.VITE_BASE,
    plugins: vitePlugins(env),                   // ++
  };
});
Copy the code

Listening configuration file

The installation

We define constants in the constant. Ts file in the config folder. If you change the values during development, the project will be loaded automatically. At this point we need the viet-plugin-restart plug-in

yarn add vite-plugin-restart --dev
Copy the code

configuration

Configure in Viteplugins.ts

/ / vitePlugins. Ts const vitePlugins: (Plugin | Plugin []) [] = [/ /... ViteRestart ({/ / configuration monitoring file restart: ['*.config.[jt]s', '**/config/*.[jt]s'], // ++ }), ];Copy the code

summary

This article describes how to optimize the viet.config. ts configuration, automatically import vue on demand, vue-Router, Pinia API, automatically import components on demand, start project optimization speed, listen for configuration file changes and reload the page. The plugins of vite.config.ts were separately extracted.

Refer to the article

Several plug-ins that allow your Vue code to “learn” automatically on demand – nuggets