In the last chapter, we added mockJS simulation data Vite2 + vue3 + TS + ElementPlus to build background management system from zero.
This chapter will refine the configuration files and add common plug-ins
1. Obtain the environment variables configured by. Env
Environment variables in the.env.* file can be obtained in the project by importing.meta.env
But import.meta.env is not used in the viet.config. ts configuration file
Get the environment variable parameters in viet.config. ts first
- Modify the.env.development file:
VITE_PORT = 60001
VITE_USE_MOCK = true
VITE_GLOB_APP_TITLE = Vue3-ElementPlus-Vite2
VITE_GLOB_API_URL = /basic-api
VITE_PUBLIC_PATH = /
VITE_BUILD_COMPRESS = 'none'
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE = false
Copy the code
Env. Production file with corresponding modifications to.env. Development file
- New SRC /utils/env.ts file handling environment variables
Env. Ts:
export function wrapperEnv(envConf: Recordable) :ViteEnv {
const ret: any = {};
for (const envName of Object.keys(envConf)) {
let realName = envConf[envName].replace(/\\n/g.'\n');
realName = realName === 'true' ? true : realName === 'false' ? false : realName;
if (envName === 'VITE_PORT') {
realName = Number(realName);
}
ret[envName] = realName;
process.env[envName] = realName;
}
return ret;
}
Copy the code
Import wrapperEnv in vite. Config. ts and loadEnv from ‘vite’ :
import { wrapperEnv } from ‘./src/utils/env’
import { defineConfig, ConfigEnv, UserConfigExport, loadEnv } from ‘vite’
ViteEnv, loadEnv, wrapperEnv, loadEnv, wrapperEnv
export default ({ command, mode }: ConfigEnv): UserConfigExport= > {
const isBuild = command === 'build'
const root = process.cwd() / / new
const env = loadEnv(mode, root) / / new
const viteEnv = wrapperEnv(env) / / new
const {
VITE_PORT,
VITE_USE_MOCK,
VITE_BUILD_COMPRESS,
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE
} = viteEnv / / new
returndefineConfig({ ...... })}Copy the code
2. Add vite – plugin – SVG – the ICONS
- Vite-plugin-svg-icons: Handles SVG /icon images
SvgBuilder also implemented the processing of SVG /icon image plug-in before, the implementation of the relatively rough, but can understand the development of vite plug-in ideas. Here you can first remove the SRC/plugins/svgBuilder js
- The installation
npm install vite-plugin-svg-icons -D
- Add configSvGiconsplugin. ts in the SRC /plugins directory
ConfigSvgIconsPlugin. Ts:
/** * Vite Plugin for fast creating SVG sprites. * https://github.com/anncwb/vite-plugin-svg-icons */
import type { Plugin } from 'vite';
import SvgIconsPlugin from 'vite-plugin-svg-icons';
import path from 'path';
export function configSvgIconsPlugin(isBuild: boolean) :Plugin {
const svgIconsPlugin:Plugin = SvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')].svgoOptions: isBuild,
// default
symbolId: 'icon-[dir]-[name]'});return svgIconsPlugin;
}
Copy the code
You then import configSvgIconsPlugin in the viet.config. ts file to use in plugins
import { configSvgIconsPlugin } from ‘./src/plugins/configSvgIconsPlugin’
plugins:[
...
configSvgIconsPlugin(isBuild)
]
Copy the code
See the plugin usage documentation here: vite-plugin-svG-icons
3. Improve the vite – plugin – style – import
- Viet-plugin-style-import: Load component library plug-ins on demand
The way Element-Plus currently loads the plugin, viet-plugin-style-import, on demand is not very elegant
-
Start by removing the styleImport code
-
The installation
npm install vite-plugin-style-import -D
- Again in the SRC/plugins directory feature: configStyleImportPlugin. Ts
ConfigStyleImportPlugin. Ts:
import type { Plugin } from 'vite';
import styleImport from 'vite-plugin-style-import';
export function configStyleImportPlugin(isBuild? :boolean) :Plugin{
return styleImport({
libs: [{libraryName: 'element-plus'.esModule: true.ensureStyleFile: true.resolveStyle: (name) = > {
name = name.slice(3)
return `element-plus/packages/theme-chalk/src/${name}.scss`
},
resolveComponent: (name) = > {
return `element-plus/lib/${name}`}}]})}Copy the code
You then import the configStyleImportPlugin in the viet.config. ts file to use in plugins
import { configStyleImportPlugin } from ‘./src/plugins/configStyleImportPlugin’
plugins:[
...
configStyleImportPlugin(isBuild)
]
Copy the code
See the plugin usage documentation here: viet-plugin-style-import
4. Add vite – plugin – HTML
- Viet-plugin-html: EJS tag processing in HTML
This plugin can add EJS tags to index. HTML, for example:
<head>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
<title><%- title %></title>
<%- injectScript %>
</head>
Copy the code
Title and injectScript are the data that can be injected
- The installation
npm install vite-plugin-html -D
- Add confightmlPlugin. ts in the SRC /plugins directory
ConfigHtmlPlugin. Ts:
import type { Plugin } from 'vite';
import html from 'vite-plugin-html';
import pkg from '.. /.. /package.json';
export function configHtmlPlugin(env: ViteEnv, isBuild: boolean) {
const { VITE_GLOB_APP_TITLE, VITE_PUBLIC_PATH } = env;
const path = VITE_PUBLIC_PATH.endsWith('/')? VITE_PUBLIC_PATH :`${VITE_PUBLIC_PATH}/ `;
const getAppConfigSrc = () = > {
return `${path || '/'}_app.config.js? v=${pkg.version}-The ${new Date().getTime()}`;
};
const htmlPlugin: Plugin[] = html({
minify: isBuild,
inject: {
// Inject data into ejs template
injectData: {
title: VITE_GLOB_APP_TITLE,
},
// Embed the generated app.config.js file
tags: isBuild?[
{
tag: 'script'.attrs: {
src: getAppConfigSrc(),
},
},
]:[]
},
});
return htmlPlugin;
}
Copy the code
Then import the configHtmlPlugin in the viet.config. ts file and use it in plugins
import { configHtmlPlugin } from ‘./src/plugins/configHtmlPlugin’
plugins:[
...
configHtmlPlugin(viteEnv, isBuild),
]
Copy the code
See the plugin usage documentation here: viet-plugin-html
5. Add vite – plugin – compression will
- Viet-plugin-compression: resource compression plug-in
- The installation
npm install vite-plugin-compression -D
- Added configCompressplugin. ts in the SRC /plugins directory
ConfigCompressPlugin. Ts:
import type { Plugin } from 'vite';
import compressPlugin from 'vite-plugin-compression';
export function configCompressPlugin(
compress: 'gzip' | 'brotli' | 'none',
deleteOriginFile: boolean = false
) :Plugin | Plugin[] {
const compressList = compress.split(0);
const plugins: Plugin[] = [];
if (compressList.includes('gzip')) {
plugins.push(
compressPlugin({
ext: '.gz',
deleteOriginFile,
})
);
}
if (compressList.includes('brotli')) {
plugins.push(
compressPlugin({
ext: '.br'.algorithm: 'brotliCompress',
deleteOriginFile,
})
);
}
return plugins;
}
Copy the code
You then import configCompressPlugin in the viet.config. ts file to use in plugins
import { configCompressPlugin } from ‘./src/plugins/configCompressPlugin’
plugins:[
...
configCompressPlugin( VITE_BUILD_COMPRESS, VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE)
]
Copy the code
See the documentation for the plugin usage here: viet-plugin-compression
6. Add a global TS type declaration
ViteEnv type declaration is used but not declared in the confightmlPlugin. ts file, now add it
- Add types/global.d.ts in the root directory
Global. Which s:
declare type Recordable<T = any> = Record<string, T>
interface ImportMetaEnv extends ViteEnv {
__: unknown
}
declare interface ViteEnv {
VITE_GLOB_APP_TITLE: string
VITE_PUBLIC_PATH: string
VITE_GLOB_API_URL: string
VITE_PORT: number
VITE_USE_MOCK: boolean
VITE_BUILD_COMPRESS: string
VITE_BUILD_COMPRESS_DELETE_ORIGIN_FILE: boolean
}
Copy the code
Json configuration items typeRoots and include
{
compilerOptions:{
...
"typeRoots": ["./node_modules/@types/"."./types"].// Declare the file directory, default node_modules/@types
"include": [
"src/**/*.ts"."src/**/*.d.ts"."src/**/*.tsx"."src/**/*.vue"."mock/**/*.ts"."types/**/*.d.ts"."types/**/*.ts",]}}Copy the code
This allows you to write some global type declarations in global.d.ts
The last
So far, the basic improvement of the background management system environment configuration.
Welcome everyone’s advice, look forward to your thumbs up oh. 😄 😄 😄