vue3+ts項目搭建和封裝(上篇)

這是我參與8月更文挑戰的第10天,活動詳情查看:8月更文挑戰javascript

1. 首先,要確保本身的node版本 >= 12.0.0, 在命令行執行node-v就能夠查看node版本

若是node版本低於12的話,就...css

node有一個模塊叫n,是專門用來管理node.js的版本的。
第一步:首先安裝n模塊:
npm install -g n

第二步:升級node倒最新穩定版
n stable
(n後面也能夠跟版本號)
n v14.15.1
或者
n 14.15.1

## 就完事兒了
複製代碼

2. 開始搭建項目

首先進入須要建立項目的路徑下html

使用npm: npm init @vitejs/app xxx xxx是項目名前端

使用yarn:yarn create @vitejs/app xxx xxx是項目名vue

image.png 而後:java

? Project name: enter
? Select a template: ...   vue
? Select a variant: vue-ts

##就完事兒了
複製代碼

獲得一個乾乾淨淨的vue3.0 + typescript項目了node

image.png

前端技術框架部分

這裏用到了vuex4.0,vue-router4.0,axios,element-plusvitewebpack

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

還有sassweb

npm install sass --D

image.png

配置項目

用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
複製代碼

image.png

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圖標

image.png

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')
複製代碼

醬紫,就能夠啦。(用法)

image.png

  • name是svg的名稱
  • color是svg的顏色

最後

公衆號:小何成長,佛系更文,都是本身曾經踩過的坑或者是學到的東西

有興趣的小夥伴歡迎關注我哦,我是:何小玍。你們一塊兒進步鴨

相關文章
相關標籤/搜索