1. 首先,要确保自己的node版本 >= 12.0.0, 在命令行执行node-v就可以查看node版本
如果node版本低于12的话,就...
node有一个模块叫n,是专门用来管理node.js的版本的。
第一步:首先安装n模块:
npm install -g n
第二步:升级node倒最新稳定版
n stable
(n后面也可以跟版本号)
n v14.15.1
或者
n 14.15.1
## 就完事儿了
2. 开始搭建项目
首先进入需要创建项目的路径下
使用npm: npm init @vitejs/app xxx xxx是项目名
使用yarn:yarn create @vitejs/app xxx xxx是项目名
然后:
? Project name: enter
? Select a template: ... vue
? Select a variant: vue-ts
##就完事儿了
得到一个干干净净的vue3.0 + typescript项目了
前端技术框架部分
这里用到了vuex4.0,vue-router4.0,axios,element-plus和vite
npm install vuex@next vue-router@next -S axios element-plus vite
还有sass
npm install sass --D
配置项目
用vite创建初始vue项目后,会生成一个默认的vite.config.ts文件,内容如下:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()]
})
然后我们开始配置vite.config.ts, 并且会在代码中以注释的形式进行说明
// 使用 defineConfig 帮手函数,这样不用 jsdoc 注解也可以获取类型提示
import { defineConfig } from "vite"
import vue from "@vitejs/plugin-vue"
// 此处引用了path路径导向
import path from "path"
// 这里引用了svg-icon,后面会讲解
import { createSvg } from './src/icons/index'
export default defineConfig({
// 查看 插件 API 获取 Vite 插件的更多细节 https://www.vitejs.net/guide/api-plugin.html
plugins: [
vue(),
// 这里引用了svg-icon,后面会讲解说明
createSvg('./src/icons/svg/')
],
// 在生产中服务时的基本路径
base: "./",
// 配置别名绝对路径 https://webpack.js.org/configuration/resolve/
resolve: {
// resolve.alias: 更轻松地为import或require某些模块创建别名
alias: {
// 如果报错__dirname找不到,需要安装node,执行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"),
},
},
// 与根相关的目录,构建输出将放在其中,如果目录存在,它将在构建之前被删除
// @default 'dist'
build: {
outDir: "dist",
},
server: {
https: false, // 是否开启 https
open: true, // 是否自动在浏览器打开
port: 8001, // 端口号
host: "0.0.0.0",
// 跨域代理
proxy: {
"/api": {
target: "http://localhost:3000", // 后台接口
changeOrigin: true,
// secure: false, // 如果是https接口,需要配置这个参数
// ws: true, //websocket支持
// 截取api,并用api代替
// rewrite: (path) => path.replace(/^\/api/, "/api"),
},
},
},
// 引入第三方的配置
optimizeDeps: {
include: [],
},
})
tsconfig.json配置
由于开发包含ts的项目经常要配置tsconfig.json,所以自己梳理了一份tsconfig.json文件;
里面包含了一些常用的tsconfig选项以及注解:
{
"compilerOptions": {
"allowUnreachableCode": true, // 不报告执行不到的代码错误。
"allowUnusedLabels": false, // 不报告未使用的标签错误
"alwaysStrict": false, // 以严格模式解析并为每个源文件生成 "use strict"语句
"experimentalDecorators": true, // 启用实验性的ES装饰器
"noImplicitAny": false, // 是否默认禁用 any
"removeComments": true, // 是否移除注释
"target": "esnext",// 编译的目标是什么版本的
"module": "esnext", // "commonjs" 指定生成哪个模块系统代码
"strict": true,
"jsx": "preserve", // 在 .tsx文件里支持JSX
"importHelpers": true,
"moduleResolution": "node",
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"suppressImplicitAnyIndexErrors": true,
"sourceMap": true, // 是否生成map文件
"baseUrl": ".", // 工作根目录
// "outDir": "./dist", // 输出目录
"declaration": true, // 是否自动创建类型声明文件
"declarationDir": "./lib", // 类型声明文件的输出目录
"allowJs": true, // 允许编译javascript文件。
"types": [
"webpack-env",
"node"
], //指定引入的类型声明文件,默认是自动引入所有声明文件,一旦指定该选项,则会禁用自动引入,改为只引入指定的类型声明文件,如果指定空数组[]则不引用任何文件
"paths": { // 指定模块的路径,和baseUrl有关联,和webpack中resolve.alias配置一样
"@/*": ["src/*"],
"@assets/*": ["src/assets/*"],
"@components/*": ["src/components/*"],
"@views/*": ["src/views/*"],
"@store/*": ["src/store/*"],
},
"lib": [// 编译过程中需要引入的库文件的列表
"es5",
"es2015",
"es2016",
"es2017",
"es2018",
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
// 指定一个匹配列表(属于自动指定该路径下的所有ts相关文件)
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue"
],
"exclude": [
"node_modules",
"src/assets/json/*.json",
"src/assets/css/*.scss"
]
}
svg-icon的配置
1. 首先引入svg插件
yarn add svg-sprite-loader -D
// 或者
npm install svg-sprite-loader -D
2. 创建文件
在@/src里面创建icons文件夹,里面创建index.vue(svgicon的模板文件), index.ts(svgicon的js逻辑), svg文件夹(svg图标存放的地址)
index.vue(svgicon的模板文件)
这部分需要用到fs模块,所以需要:
yarn add fs
// 或者
npm install fs
<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>
index.ts(svg的js逻辑文件)
这部分有问题的小伙伴可以找我,我写了注释的。
import { readFileSync, readdirSync } from 'fs'
let idPerfix = ''
const svgTitle = /<svg([^>+].*?)>/
const clearHeightWidth = /(width|height)="([^>+].*?)"/g
const hasViewBox = /(viewBox="[^>+].*?")/g
const clearReturn = /(\r)|(\n)/g
// 查找svg文件
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
}
// 生成svg
export 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>`
)
}
}
}
svg存放svg图标
3. 在vite.config.ts里面引用svg
import { defineConfig } from "vite"
import { createSvg } from './src/icons/index'
export default defineConfig({
plugins: [
vue(),
createSvg('./src/icons/svg/')
]
})
4. 在main.ts中写入svg-icon模板
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')
酱紫,就可以啦。(用法)
- name是svg的名称
- color是svg的颜色
最后
公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西
有兴趣的小伙伴欢迎关注我哦,我是:何小玍。大家一起进步鸭