This is the 10th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1. First, make sure your node version is >= 12.0.0 and run it on the command linenode-vYou can view the Node version

If the node version is less than 12, then…

Node has a module called N that manages versions of Node.js. N v14.15.1 or N 14.15.1 ##Copy the code

2. Start building the project

First go to the path where you want to create the project

Use NPM: NPM init@vitejs /app XXX XXX is the project name

Use yarn: yarn create@vitejs /app XXX XXX is the project name

And then:

? Project name: enter ? Select a template: ... vue ? Select a variant: Vue-ts ##Copy the code

You’ve got a clean vue3.0 + typescript project

Front-end technical framework part

Vuex4.0,vue-router4.0,axios,element-plus, and vite are used here

npm install vuex@next vue-router@next -S axios element-plus vite

And sass

npm install sass –D

Configuration items

After creating the initial vue project with vite, a default vite. Config. ts file is generated with the following contents:

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

export default defineConfig({
  plugins: [vue()]
})
Copy the code

Then we start to configure vte.config.ts, which will be explained as comments in the code

// Use defineConfig helper function, Import {defineConfig} from "vite" import vue from "@vitejs/plugin-vue" import {defineConfig} from "vite" import vue from "@vitejs/plugin-vue Path from "path" // Import {createSvg} from './ SRC/ICONS /index' export default defineConfig({// see the plugin API for more details on the Vite plugin https://www.vitejs.net/guide/api-plugin.html plugins: CreateSvg ('./ SRC/ICONS/SVG /')], // the base path for service in production: ". / ", / / configure an alias absolute path to resolve: https://webpack.js.org/configuration/resolve/ {/ / resolve. Alias: NPM install @types/node --save-dev "@": NPM install @types/node --save-dev "@": path.resolve(__dirname, "./src"), "@assets": path.resolve(__dirname, "./src/assets"), "@components": path.resolve(__dirname, "./src/components"), "@views": path.resolve(__dirname, "./src/views"), "@store": Path.resolve (__dirname, "./ SRC /store"),},}, // Root related directory where build output will be placed, if the directory exists, it will be removed before build // @default 'dist' build: {outDir: "dist",}, server: {HTTPS: false, // Whether to enable HTTPS open: true, // Whether to automatically open in the browser port: 8001, // Port number host: "0.0.0.0", // cross-domain proxy: {"/ API ": {target: "http://localhost:3000", // changeOrigin: true, // Secure: False, // if the interface is HTTPS, you need to configure this parameter // ws: true, // WebSocket supports // intercepts apis and uses apis instead of // rewrite: (path) = > path. The replace (/ ^ \ / API /, / "API"),,}},}, / / the introduction of third-party configuration optimizeDeps: {include: [],}})Copy the code

Tsconfig. Json configuration

Since tsconfig.json is often configured for projects that include TS, I have compiled a tsconfig.json file. It contains some common tsconfig options and comments:

{"compilerOptions": {"allowUnreachableCode": true, // Do not report unreachable code errors. "AllowUnusedLabels ": false, // does not report an unused label error "alwaysStrict": False, // parse in strict mode and generate "use strict" statement for each source file "experimentalDecorators": true, // enable experimental ES decorator "noImplicitAny": False,// whether to disable any "removeComments" by default: true, // whether to remove the comment "target": "esnext",// what version of "module" was built to target: "Esnext ", // "commonjs" specifies which module to generate system code "strict": true," JSX ": "preserve", // support JSX "importHelpers" in.tsx: true, "moduleResolution": "node", "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": True, "suppressImplicitAnyIndexErrors" : true, "sourceMap" : true, / / whether to generate map file "baseUrl" : "", work / / root / /" outDir ": // do not create type declaration file declarationDir": "./lib", // do not create type declaration file declarationDir": "./lib", // do not create type declaration file declarationDir": "./lib", // do not create type declaration file declarationDir": ". True, // allow the compilation of javascript files. "types": ["webpack-env", "node"], // specify the type declaration files to import. Default is to import all type declarations automatically. Once this option is specified, automatic import is disabled. {/ / specify the path of the module, and related to baseUrl, and resolve in webpack alias configuration "@ / *" : / SRC / * ", "@ assets / *" : / SRC/assets / * ", "@ components / *" : ["src/components/*"], "@views/*": ["src/views/*"], "@store/*": ["src/store/*"], }, "lib": [// scripthost]} [// scripthost]} [// scripthost]} / / specify a list of matching (belong to automatic all ts related documents) of the specified under this path "include:" [" SRC / / *. * * ts ", "/ SRC / * * *. The TSX", "/ SRC / * * *. Vue"], "exclude" : [ "node_modules", "src/assets/json/*.json", "src/assets/css/*.scss" ] }Copy the code

SVG – configuration icon

1. Introduce the SVG plug-in first

Yarn add SVg-sprite-loader -d or NPM install SVG-sprite-loader -dCopy the code

2. Create a file

In the @/ SRC folder I will create the ICONS folder. In the ICONS folder I will create index.vue(svgicon’s template file), index.ts(Svgicon’s JS logic) and THE SVG folder (where the SVG ICONS are stored).

Index.vue (template file for Svgicon)

This part requires the FS module, so you need to:

Yarn add fs // or NPM install fsCopy the code
<template> <svg :class="svgClass" v-bind="$attrs" :style="{ color: color }"> <use :xlink:href="iconName"></use> </svg> </template> <script setup lang="ts"> import { computed, defineProps } from 'vue' const props = defineProps({ name: { type: String, required: true }, color: { type: String, default: '' } }) const iconName = computed(() => `#icon-${ props.name }`) const svgClass = computed(() => { if(props.name) return  `svg-icon icon-${ props.name }` return 'svg-icon' }) </script> <style scoped> .svg-icon{width: 1em; height: 1em; fill:currentColor; vertical-align: middle; } </style>Copy the code

Index. ts(SVG js logical file)

If you have any questions about this, you can call me. I’ve annotated it.

import { readFileSync, readdirSync } from 'fs' let idPerfix = '' const svgTitle = /<svg([^>+].*?) >/ const clearHeightWidth = /(width|height)="([^>+].*?) "/g const hasViewBox = /(viewBox="[^>+].*?" )/g const clearReturn = / (\ r) | (\ n)/g / / find SVG files function svgFind (e) {const arr = [] const dirents = readdirSync (e. { withFileTypes: true }) for (const dirent of dirents) { if (dirent.isDirectory()) arr.push(... svgFind(e + dirent.name + '/')) else { const svg = readFileSync(e + dirent.name) .toString() .replace(clearReturn, '') .replace(svgTitle, ($1, $2) => { let width = 0, height = 0, 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>') arr.push(SVG)}} return arr} // Generate const createSvg = (path: any, perfix = 'icon') => { if (path === '') return idPerfix = perfix const res = svgFind(path) return { name: 'svg-transform', transformIndexHtml(dom: String) { return dom.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

SVG holds SVG ICONS

3. Reference SVG in vite. Config. ts

import { defineConfig } from "vite" import { createSvg } from './src/icons/index' export default defineConfig({ plugins:  [ vue(), createSvg('./src/icons/svg/') ] })Copy the code

4. Write in main.tssvg-iconThe template

import { createApp } from 'vue'
import App from './App.vue'
import svgIcon from './icons/index.vue'

const app = createApp(App)

app
.component('svg-icon', svgIcon)
.mount('#app')
Copy the code

Maozi, that’s it. (use)

  • Name is the name of SVG
  • Color is the color of SVG

The last

Public number: xiao He growth, The Buddha department more text, are their own once stepped on the pit or is learned

Interested partners welcome to pay attention to me, I am: He young life. Everybody progress duck together