Vue3 + Ts + ElementPlus + Vite2 Build background Management System from scratch (1)

1. Install, use, and configure Vite

Why Vite?

Installation:

  • Use NPM:

    npm init @vitejs/app

  • Or use Yarn:

    yarn create @vitejs/app

Then, use the template directly:

View the NPM version of the NPM installation template: NPM -v

This chapter uses NPM 6.x to install vuE-TS templates to view supported template presets

# npm 6X version NPM init @vitejs/app my-vue-app --template vue-ts # yarn yarn create @vitejs/app my-vue-app --template vue-tsCopy the code

After the template is installed

  • Enter the project directory: CD my-vue-app
  • Install dependency: NPM install
  • Start: NPM run dev

Open the browser: http://localhost:3000/

The vuE-TS template project built to this Vite is complete

2. Configure the alias on vite

Use the editor to open the build number project into the configuration file vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [vue()]
})
Copy the code

After the alias is configured:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
const resolve = (dir: string) = > path.join(__dirname, dir)

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [vue()],
	resolve: {
		alias: {
			The '@': resolve('src'),
			comps: resolve('src/components'),
			apis: resolve('src/apis'),
			views: resolve('src/views'),
			utils: resolve('src/utils'),
			routes: resolve('src/routes'),
			styles: resolve('src/styles')}}})Copy the code

Here you can configure aliases as you like, much like webPack

  • TS may have this error message:

    The module ‘PATH’ or its corresponding type declaration could not be found.

  • Solutions:

    npm install @types/node –save-dev

3. Configure the vite service

Port 3088 is configured. Proxy Configures the proxy serviceCopy the code

Complete document of server-options configuration items

export default defineConfig({
	plugins: [vue()],
	resolve: {
		alias: {
			The '@': resolve('src'),
			comps: resolve('src/components'),
			apis: resolve('src/apis'),
			views: resolve('src/views'),
			utils: resolve('src/utils'),
			routes: resolve('src/routes'),
			styles: resolve('src/styles')}},server: {
		// Host name of the server
		host: ' './ / the port number
		port: 3088.// Set to true to exit if a port is already occupied, instead of trying the next available port
		strictPort: false.// The server automatically opens the application in the browser when it starts. When this value is a string, it is used as the pathname of the URL
		open: false.// Customize proxy rules
		proxy: {
			// This is an option
			'/api': {
				target: 'http://jsonplaceholder.typicode.com'.changeOrigin: true.rewrite: path= > path.replace(/^\/api/.' ')}}}})Copy the code

4. Add the CSS preprocessor SASS

  • The installation

npm install -D sass sass-loader

Modify the components/HelloWorld. Vue files, style tags, add lang = "SCSS"Copy the code
<style lang="scss" scoped>
	a {
		color: #42b983;
	}

	label {
		margin: 0 0.5 em;
		font-weight: bold;
	}

	code {
		background-color: #eee;
		padding: 2px 4px;
		border-radius: 4px;
		color: # 304455;
	}
</style>
Copy the code

5. Implement Icon component

In Webpack, the svG-Sprite-loader plugin can customize its own Icon components, but requires the use of related apis such as require.context, which is not required in ViteCopy the code
  • Adding an SVG file

    Create an ICONS and an ICONS/SVG directory under SRC /assets, and then create a bug.svg file under SVG and write:

<svg width="128" height="128" xmlns="http://www.w3.org/2000/svg">
	<path
		d="M127.73.143c0 1.412-.506 2.635-1.518 3.669-1.011 1.033-2.209 1.55-3.592 1.55h-17.887c0 9.296-1.783 17.178-5.35 23.645l16.609 17.044c1.011 1.034 1.517 2.257 1.517 3.67 0 1.412-.506 2.635-1.517 3.668-.958 1.033-2.155 1.55-3.593 1.55-1.438 0-2.635-.517-3.593-1.55L -15.811-16.063a15.49 15.49 0 1-1.196 1.06c-.532.434-1.65 1.208-3.353 2.322a50.104 50.104 0 0 1-5.192-2.974 c - 1.758.87 3.94 1.658 6.546 2.364 2.607.706 5.189 1.06 7.748 1.06 V47.044 H58.89 v73.062-2.716 c 0-5.417 -. 367-8.106-1.102-2.688-734-5.003-1.631-6.945-2.692 a66.769 66.769 0 0 1-5.268-1.77-1.73-1.94-3.476-2.65 L33.9 109.34 L -14.611 16.877c-1.066 1.14-2.344 1.711-3.833 1.711-1.277 0-2.422 -. 434-3.434-1.304-1.012-978-1.557-2.187-1.635-3.627-079-1.44.333-2.705 L16.129 1.236 3.794-18.51 - c - 3.087-6.197-4.63-13.644-4.63-22.342 H5.235 0-2.58 - c - 1.383-517-3.592-1.55 s. 125 74.545.125 73.135c0-1.412.506-2.635 1.518-3.668 1.012-1.034 2.21-1.55 3.592-1.55h17.887V43.939L9.308 29.833 c-1.012-1.033-1.017-2.256-1.517-3.669 0-1.412.505-2.635 1.517-3.668 1.012-1.034 2.21-1.55 3.593-1.55s2.58.516 3.593 1.55l13.813 14.106h67.396l13.814-14.106c1.012-1.034 2.21-1.55 3.592-1.55 1.384 0 2.581.516 3.593 1.55 1.012 1.033 0-1.413. 1.518 2.256 1.518 3.668 2.636 1.518 3.67 l - 13.814 506 14.105 v23.975 h17.887 c1.383 0 2.58.516 3.593 1.55 1.011 1.033 1.517 2.256 1.517 3.668l-.005.01zm89.552 26.175h38.448 c0-7.23 2.489-13.386 7.466-18.469C50.892 2.623 56.92.082 64 .082c7.08 0 13.108 2.541 18.086 7.624 4.977 5.083 7.466 11.24 7.466 18.469z"
	/>
</svg>
Copy the code
  • Work with SVG file plug-ins

    Create the plugins folder in the SCR directory and create the svgBuilder.js file

import { readFileSync, readdirSync } from 'fs'

let idPerfix = ' '
const svgTitle = /
      
       +].*?) >/
      ([^>
const clearHeightWidth = /(width|height)="([^>+].*?) "/g

const hasViewBox = /(viewBox="[^>+].*?" )/g

const clearReturn = /(\r)|(\n)/g

function findSvgFile(dir) {
	const svgRes = []
	const dirents = readdirSync(dir, {
		withFileTypes: true
	})
	for (const dirent of dirents) {
		if(dirent.isDirectory()) { svgRes.push(... findSvgFile(dir + dirent.name +'/'))}else {
			const svg = readFileSync(dir + dirent.name)
				.toString()
				.replace(clearReturn, ' ')
				.replace(svgTitle, ($1, $2) = > {
					// console.log(++i)
					// console.log(dirent.name)
					let width = 0
					let height = 0
					let content = $2.replace(clearHeightWidth, (s1, s2, s3) = > {
						if (s2 === 'width') {
							width = s3
						} else if (s2 === 'height') {
							height = s3
						}
						return ' '
					})
					if(! hasViewBox.test($2)) {
						content += `viewBox="0 0 ${width} ${height}"`
					}
					return `<symbol id="${idPerfix}-${dirent.name.replace('.svg'.' ')}" ${content}> `
				})
				.replace('</svg>'.'</symbol>')
			svgRes.push(svg)
		}
	}
	return svgRes
}

export const svgBuilder = (path, perfix = 'icon') = > {
	if (path === ' ') return
	idPerfix = perfix
	const res = findSvgFile(path)
	// console.log(res.length)
	// const res = []
	return {
		name: 'svg-transform'.transformIndexHtml(html) {
			return html.replace(
				'<body>'.`
          <body>
            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="position: absolute; width: 0; height: 0">
              ${res.join(' ')}
            </svg>
        `)}}}Copy the code
  • Using the SVG plug-in

    Import in viet.config. ts and register in plugins

  import { svgBuilder } from './src/plugins/svgBuilder';
	/ /...
  plugins: [
    vue(),
    [svgBuilder('./src/assets/icons/svg/')] // We have already imported all the SVG under SRC/ICONS/SVG /, no need to import it separately].Copy the code

Now that this plug-in is complete, you need to refine the SvgIcon component to use components directly from SVG-Icon notes

  • SvgIcon component registration

    Create a new SvgIcon/index.vue file in the SCR/Components directory

<template> <svg :class="svgClass" aria-hidden="true" v-on="$attrs"> <use :xlink:href="iconName" /> </svg> </template> <script lang="ts"> import { defineComponent, computed } from 'vue' interface Props { iconClass: string className: string } export default defineComponent({ name: 'SvgIcon', props: { iconClass: { type: String, required: true }, className: { type: String, default: () => '' } }, setup(props: Props) { const iconName = computed((): string => `#icon-${props.iconClass}`) const svgClass = computed((): string => { if (props.className) { return 'svg-icon ' + props.className } else { return 'svg-icon' } }) return { iconName, svgClass } } }) </script> <style scoped> .svg-icon { width: 1em; height: 1em; Vertical - align: 0.15 em. fill: currentColor; overflow: hidden; } </style>Copy the code

The main.ts file is imported and registered

import SvgIcon from ‘./components/SvgIcon/index.vue’

createApp(App).component(‘svg-icon’, SvgIcon).mount(‘#app’)

Test it in app.vue

When this is done, you can see the crawler icon on the interface