vite+vue3.0+ts搭建项目

项目git地址:https://gitee.com/suyong01/vue3-ts-template

vue+ts+vite项目初始化

# npm 6.x
npm init @vitejs/app $appName --template vue-ts
# npm 7+, extra double-dash is needed:
npm init @vitejs/app $appName -- --template vue-ts
# yarn
yarn create vite my-vue-app --template vue-ts

 

接下来需要安装:

@types/node:作用是找不到模块“path”或其相应的类型声明 或者 找不到名称“__dirname”等

yarn add @types/node -D

 修改.gitignore,删掉.vscode/*

代码规范和提交规范

  代码规范化:EditorConfig + Prettier + ESLint

  提交规范化:husky + lint-staged + commitlint

  生成ChangeLog:standard-version

Prettier

yarn add prettier -D

安装完成后,在根目录创建 prettier.config.js配置参考Configuration File · Prettier

// https://prettier.io/docs/en/configuration.html
module.exports = {
  // 每一行的宽度(显示的字符数)
  printWidth: 120,

  // tab健的空格数
  tabWidth: 2,

  // 是否在对象中的括号之间打印空格,{a:5}格式化为{ a: 5 }
  bracketSpacing: true,

  // 箭头函数的参数无论有几个,都要括号包裹
  arrowParens: "always",

  // 换行符的使用
  endOfLine: "lf",

  // 是否用单引号, 项目中全部使用单引号
  singleQuote: true,

  // 对象或者数组的最后一个元素后面是否要加逗号
  trailingComma: "all",

  // 是否加分号,项目中统一加分号
  semi: true,

  // 是否使用tab格式化: 不使用
  useTabs: false,
};

再创建一个.prettierignore

# npm包
/node_modules
package-lock.json

# build产物
/dist
/types

# eslint
.eslintcache

# jest
/coverage

# docs api文档
/docs

#webstorm
.idea

 ESLint

 安装以下插件

yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-import -D

安装 airbnb-base,后面会用到

yarn add eslint-config-airbnb -D

安装成功后执行以下指令对ESLint进行配置

npx eslint --init
  • How would you like to use ESLint?

选择第三条 To check syntax, find problems, and enforce code style ,检查语法、检测问题并强制代码风格。

  • What type of modules does your project use?

项目非配置代码都是采用的 ES6 模块系统导入导出,选择 JavaScript modules

  • Which framework does your project use?

根据实际需要选择,本文这里选择都不要

  • Does your project use TypeScript?

因为是TypeScript项目,这里当然选是啦

  • Where does your code run?

Browser 和 Node 环境都选上

  • How would you like to define a style for your project?

选择 Use a popular style guide ,即使用社区已经制定好的代码风格,我们去遵守就行。

  • Which style guide do you want to follow?

选择 Airbnb 风格,都是社区总结出来的最佳实践。

  • What format do you want your config file to be in?

选择 JavaScript ,即生成的配置文件是 js 文件,配置更加灵活。

  • Would you like to install them now with npm?

选择YES

然后在 package.json 中加上scripts指令,然后在build指令前加上 npm run lint
{
    "lint": "eslint src",
    "build": "npm run lint && vue-tsc --noEmit && vite build",
}
我们之前选择风格的时候,选择了 Airbnb 风格,所以很多 rules 规则就不需要我们再自己去定制,直接在 extends 里引入即可,Airbnb github地址github.com/airbnb/java… 

安装结束后,项目根目录下多出了新的文件 .eslintrc.js,修改如下:

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  extends: [
    'airbnb-base',
    'plugin:@typescript-eslint/recommended',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    // ecmaVersion用来指定你想要使用的 ECMAScript 版本
    ecmaVersion: 12,
    sourceType: 'module',
  },
  plugins: ['@typescript-eslint', 'import'],
  rules: {
    'import/no-unresolved': 'off',
    'import/extensions': 'off',
  },
};

再新建一个 .eslintignore

# npm包
/node_modules
package-lock.json

# build产物
/dist
/types

# eslint
.eslintcache

# jest
/coverage

# docs api文档
/docs

# webpack 配置
/scripts

#webstorm
.idea
  # 自动引入生成文件
  auto-imports.d.ts
  components.d.ts

这时我们已经同时安装了Prettier和ESLint,它们俩之间会有一些重复冲突的配置,我们还需要一些插件,以便能够和ESLint一起使用

冲突的本质在于 eslint 既负责了代码质量检测,又负责了一部分的格式美化工作,格式化部分的部分规则和 prettier 不兼容。 能不能让 eslint 只负责代码质量检测而让 prettier 负责美化呢? 社区有了非常好的成熟方案,即 eslint-config-prettier 加上 eslint-plugin-prettier。
安装这两个插件:
yarn add eslint-plugin-prettier eslint-config-prettier -D
  • eslint-config-prettier 的作用是关闭 eslint 中与 prettier 相互冲突的规则。
  • eslint-plugin-prettier 的作用是调用 ESLint 的时候调用 Prettier 的规范进行代码风格校验

在 .eslintrc.js 添加 prettier 插件:

module.exports = {
  ...
  extends: [
    'plugin:prettier/recommended' // 添加 prettier 插件
  ],
  ...
}

vscode插件 EditorConfig

在项目左侧列表,直接右键,底下会有 Generate .editorconfig ,点击即可快速生成

修改它生成的 .editorconfig 文件:

# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]                   # 表示所有文件都要遵循
indent_style = space              # 缩进风格,可选配置有space和tab
indent_size = 2                   # 缩进大小
end_of_line = lf                  # 换行符,可选配置有lf、cr和crlf
charset = utf-8                   # 编码格式,通常都是选utf-8
trim_trailing_whitespace = true   # 去除多余的空格
insert_final_newline = true       # 在尾部插入一行

[*.md]                # 表示仅 md 文件适用
insert_final_newline = false      # 在尾部插入一行
trim_trailing_whitespace = false  # 去除多余的空格

vscode插件 Prettier-Code formatter

配置这个的目的就是为了让开发者的 vscode 配置保持统一,该文件的配置优先于 vscode 全局的settings.json,这样别人下载了你的项目进行开发,也不会因为全局 settings.json的配置不同而导致 Prettier 或之 Eslint 失效。

在.vscode文件夹下新建 settings.json 文件,配置如下:

{
  // 指定哪些文件不参与搜索
  "search.exclude": {
    "**/node_modules": true,
    "dist": true
  },
  "editor.formatOnSave": true,
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

这里配置的效果是:是在我们保存时,会自动执行一次 Prettier 代码格式化

配置.prettierrc文件

在根目录下添加 .prettierrc 文件

{
  "useTabs": false, // 使用tab缩进还是空格缩进
  "tabWidth": 2, // tab是空格的情况下,是几个空格
  "singleQuote": true, // 使用单引号还是双引号
  "semi": true, // 语句末尾是否要加分号,默认值true
  "trailingComma": "none", // 在多行输入的尾逗号是否添加
  "vueIndentScriptAndStyle": false, // 是否给vue中的 <script> and <style>标签加缩进
  "bracketSpacing": true, // 是否在对象的{}内部两侧加空格
  "htmlWhitespaceSensitivity": "strict" // 是否显示HTML文件中的空格。 有效选项: 'css' - 尊重CSS display属性的设置。 'strict' - 空格被认为是敏感的。 'ignore' - 空格被认为是不敏感的
}

全量说明,按需使用

{
  printWidth: 80, // 超过最大值换行
  tabWidth: 2, // 缩进字节数
  useTabs: false, // 缩进不使用tab,使用空格
  semi: true, // 句尾添加分号
  singleQuote: false, // 使用单引号代替双引号
  quoteProps: 'as-needed', // 对象的key是否用引号括起来,有三种选项 "as-needed"|"consistent"|"preserve"
  jsxSingleQuote: false, // 在jsx中使用单引号代替双引号
  trailingComma: 'es5', // 选项:none|es5|all, 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
  bracketSpacing: true, // 是否在对象的{}内部两侧加空格 true - { foo: bar } false - {foo: bar}.
  jsxBracketSameLine: false, // 在jsx中把'>' 是否单独放一行
  arrowParens: 'avoid', // (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号 'bracketSpacing': true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
  rangeStart: 0, // 仅格式化选中文本 选中文本格式化的起始位置
  rangeEnd: Infinity, // 选中文本格式化的结束位置
  parser: 'babylon', // 格式化的解析器,默认是babylon,会自动根据输入文件推断,不用更改设置
  requirePragma: false, // 若为true,文件顶部加了 /*** @prettier */或/*** @format */的文件才会被格式化
  insertPragma: false, // 当requirePragma参数为true时,此参数为true将向@format标记后面添加一个换行符
  proseWrap: 'preserve', // 有效选项[always|never|preserve]。当Markdown文本超过printWidth时,是否换行,always-换行 never-不换行 preserve保持原样
  endOfLine: 'lf', // 结尾是 lf-\n cr-\r lfcr-\n\r  auto-保持现有的行尾设置
  htmlWhitespaceSensitivity: 'css', // 是否显示HTML文件中的空格。 有效选项: 'css' - 尊重CSS display属性的设置。 'strict' - 空格被认为是敏感的。 'ignore' - 空格被认为是不敏感的
  vueIndentScriptAndStyle: false, // 是否给vue中的 <script> and <style>标签加缩进
  embeddedLanguageFormatting: 'auto', // 是否格式化嵌入到JS中的html标记的代码段或者Markdown语法 auto-格式化 off-不格式化
}

vscode插件 ESLint

再到之前创建的 .vscode/settings.json 中添加上以下代码:

{
  "eslint.validate": [
    "javascript",
    "typescript"
  ],
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
}

这时候我们保存时,就会开启 eslint 的自动修复,帮我们修复一些语法上的写法问题。

husky + lint-staged 提交规范的代码

首先,使用husky和lint-staged之前,我们先检查一下自己的node版本是否>=12.20.0,如果小于,请重装node或者用nvm进行版本切换,见官方要求:github.com/okonet/lint…

在项目开发过程中,每次提交前我们都要对代码进行格式化以及 eslint 和 stylelint 的规则校验,以此来强制规范我们的代码风格,以及防止隐性 BUG 的产生。

那么有什么办法只对我们 git 缓存区最新改动过的文件进行以上的格式化和 lint 规则校验呢?

答案就是 husky ,它会提供一些钩子,比如执行 git commit 之前的钩子 pre-commit ,借助这个钩子我们就能执行 lint-staged 所提供的代码文件格式化及 lint 规则校验。

我们直接执行官方推荐的安装指令:
npx mrm@2 lint-staged

注意:安装huskylint-staged之前,请先安装 ESLint + Prettier ,否则会检测到没有安装后报错:

官方推荐的安装指令执行时会帮你做这几件事:

  • package.json 的devDependencies里加上 huskylint-staged 两个依赖
  • package.json 里的scripts里加上 "prepare": "husky install" 脚本
  • 往 package.json 里增加 lint-staged 配置项
  • 在根目录新建.husky文件夹,文件夹里的pre-commit文件已经自动帮我们集成了npx lint-staged指令
到这里已经可以实现:在commit提交时,对暂存区的.js文件都执行eslint --cache --fix进行语法自动修正,但是官方给配置的里面没有包含.ts的文件,且我们并不想要自动修正。
重新配置我们的package.json,修改指令自动生成的lint-staged配置项为我们所需要的
{
  "lint-staged": {
    "*.{ts,js}": [
      "eslint"
    ]
  }
}

这段话的意思是:当暂存区内的文件后缀为.js或者.ts时,就会进行eslint校验。

如此配置完之后,我们每次进行commit时,都会触发eslint校验,去检测暂存区里的文件是否符合ESLint规范,如果不符合规范,就会抛错出来中止commit。

commitlint 提交规范的 commit

在多人参与的项目中,如果 git 的提交说明清晰,在后期协作以及 bug 处理时会变得有据可查。这里,我们使用社区最流行、最知名、最受认可的 Angular 团队提交规范每个 commit 都是有着清楚的完整的格式的,commit message 由 Header、Body、Footer 组成

我们的目的只有一个:只让符合 Angular 规范的 commit message 通过 commit 检查,为了达成这个目的,我们使用 commitlint 可以帮助我们检查 git commit 时的 message 格式是否符合规范

我们首先安装依赖

yarn add @commitlint/cli @commitlint/config-conventional -D

在根目录新建 .commitlintrc.js 文件,这就是我们的 commitlint 配置文件,配置如下:

module.exports = {
  extends: ['@commitlint/config-conventional'],
  rules: {
    'type-enum': [
      2,
      'always',
      ['build', 'ci', 'chore', 'docs', 'feat', 'fix', 'perf', 'refactor', 'revert', 'style', 'test'],
    ],
  },
};

其中都是官方推荐的 angular 风格的 commitlint 配置

/**
 * build : 改变了build工具 如 webpack
 * ci : 持续集成新增
 * chore : 构建过程或辅助工具的变动
 * feat : 新功能
 * docs : 文档改变
 * fix : 修复bug
 * perf : 性能优化
 * refactor : 某个已有功能重构
 * revert : 撤销上一次的 commit
 * style : 代码格式改变
 * test : 增加测试
 */

然后我们要结合上面的 husky 增加一个钩子

#windows
npx husky add .husky/commit-msg "npx"

#其他系统,windows下无法add
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit $1'

注意:windows系统下,在npx husky add时可能会出现无法add的情况,执行完上述指令后,还需要在生成的 commit-msg 文件中手动补全一下。

补全后的 commit-msg 文件完整配置如下:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install commitlint --edit $1 

 commitizen

安装

npm i commitizen -g

初始化

#npm
commitizen init cz-conventional-changelog --save-dev --save-exact
#yarn
commitizen init cz-conventional-changelog --yarn --dev --exact

初始化命令主要进行了3件事情

  1. 在项目中安装cz-conventional-changelog 适配器依赖

  2. 将适配器依赖保存到package.jsondevDependencies字段信息

  3. package.json中新增config.commitizen字段信息,主要用于配置cz工具的适配器路径:

    "devDependencies": {
     "cz-conventional-changelog": "^2.1.0"
    },
    "config": {
      "commitizen": {
        "path": "./node_modules/cz-conventional-changelog"
      }
    }

 接下来可以使用cz的命令git cz代替git commit进行提交说明。

cz-customizable

定制项目的提交说明

yarn add cz-customizable -D

将之前符合Angular规范的cz-conventional-changelog适配器路径改成cz-customizable适配器路径:

"devDependencies": {
  "cz-customizable": "^5.3.0"
},
"config": {
  "commitizen": {
    "path": "node_modules/cz-customizable"
  }
}

新建 .cz-config.js 

module.exports = {
  // type 类型(定义之后,可通过上下键选择)
  types: [
    { value: 'feat', name: 'feat:     新增功能' },
    { value: 'fix', name: 'fix:      修复 bug' },
    { value: 'docs', name: 'docs:     文档变更' },
    { value: 'style', name: 'style:    代码格式(不影响功能,例如空格、分号等格式修正)' },
    { value: 'refactor', name: 'refactor: 代码重构(不包括 bug 修复、功能新增)' },
    { value: 'perf', name: 'perf:     性能优化' },
    { value: 'test', name: 'test:     添加、修改测试用例' },
    { value: 'build', name: 'build:    构建流程、外部依赖变更(如升级 npm 包、修改 webpack 配置等)' },
    { value: 'ci', name: 'ci:       修改 CI 配置、脚本' },
    { value: 'chore', name: 'chore:    对构建过程或辅助工具和库的更改(不影响源文件、测试用例)' },
    { value: 'revert', name: 'revert:   回滚 commit' }
  ],

  // scope 类型(定义之后,可通过上下键选择)
  scopes: [
    ['components', '组件相关'],
    ['hooks', 'hook 相关'],
    ['utils', 'utils 相关'],
    ['ui', '对 ui 的调整'],
    ['styles', '样式相关'],
    ['deps', '项目依赖'],
    ['auth', '对 auth 修改'],
    ['other', '其他修改'],
    // 如果选择 custom,后面会让你再输入一个自定义的 scope。也可以不设置此项,把后面的 allowCustomScopes 设置为 true
    ['custom', '以上都不是?我要自定义']
  ].map(([value, description]) => {
    return {
      value,
      name: `${value.padEnd(30)} (${description})`
    }
  }),

  // 是否允许自定义填写 scope,在 scope 选择的时候,会有 empty 和 custom 可以选择。
  // allowCustomScopes: true,

  // allowTicketNumber: false,
  // isTicketNumberRequired: false,
  // ticketNumberPrefix: 'TICKET-',
  // ticketNumberRegExp: '\\d{1,5}',


  // 针对每一个 type 去定义对应的 scopes,例如 fix
  /*
  scopeOverrides: {
    fix: [
      { name: 'merge' },
      { name: 'style' },
      { name: 'e2eTest' },
      { name: 'unitTest' }
    ]
  },
  */

  // 交互提示信息
  messages: {
    type: '确保本次提交遵循 Angular 规范!\n选择你要提交的类型:',
    scope: '\n选择一个 scope(可选):',
    // 选择 scope: custom 时会出下面的提示
    customScope: '请输入自定义的 scope:',
    subject: '填写简短精炼的变更描述:\n',
    body: '填写更加详细的变更描述(可选)。使用 "|" 换行:\n',
    breaking: '列举非兼容性重大的变更(可选):\n',
    footer: '列举出所有变更的 ISSUES CLOSED(可选)。 例如: #31, #34:\n',
    confirmCommit: '确认提交?'
  },

  // 设置只有 type 选择了 feat 或 fix,才询问 breaking message
  allowBreakingChanges: ['feat', 'fix'],

  // 跳过要询问的步骤
  // skipQuestions: ['body', 'footer'],

  // subject 限制长度
  subjectLimit: 100,
  breaklineChar: '|', // 支持 body 和 footer
  // footerPrefix : 'ISSUES CLOSED:'
  // askForBreakingChangeFirst : true,
}

 额外安装一个依赖

yarn add -D eslint-plugin-vue

修改 .eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
    node: true,
  },
  globals: {
    defineEmits: true,
    document: true,
    localStorage: true,
    GLOBAL_VAR: true,
    window: true,
    defineProps: true,
    defineExpose: true,
  },
  extends: [
    './.eslintrc-auto-import.json',
    'airbnb-base',
    'plugin:@typescript-eslint/recommended',
    'plugin:vue/vue3-recommended',
    'plugin:prettier/recommended', // 添加 prettier 插件
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    parser: '@typescript-eslint/parser',
    sourceType: 'module',
  },
  plugins: ['vue', '@typescript-eslint', 'import'],
  rules: {
    'no-console': 'off',
    'import/no-unresolved': 'off',
    'import/extensions': 'off',
    'import/no-extraneous-dependencies': 'off',
  },
};

配置alias别名

在vite.config.ts中

import path from 'path';

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: { find: '@', replacement: path.resolve(__dirname, 'src') }
  }
})

在tsconfig.json中

{
  "compilerOptions": {
    "target": "esnext",
    "useDefineForClassFields": true,
    "module": "esnext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    // 添加如下配置
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"]
    },
    "lib": ["esnext", "dom"]
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

 配置vite服务

在vite.config.ts中,有些选项根据需要自己选择

server: {
    host: true, // host设置为true才可以使用network的形式,以ip访问项目
    port: 8080, // 端口号
    open: false, // 自动打开浏览器
    cors: true, // 跨域设置允许
    strictPort: false, // 如果端口已占用直接退出
    // 接口代理
    proxy: {
      '/api': {
        // 本地 8000 前端代码的接口 代理到 8888 的服务端口
        target: 'http://localhost:8888/',
        changeOrigin: true, // 允许跨域
        rewrite: (path) => path.replace('/api/', '/')
      }
    }
  }

配置build打包

    build: {
minify: 'terser', brotliSize:
false, // 消除打包大小超过500kb警告 chunkSizeWarningLimit: 2000, // 在生产环境移除console.log terserOptions: { compress: { drop_console: false, pure_funcs: ['console.log', 'console.info'], drop_debugger: true, }, }, assetsDir: 'static/assets', // 静态资源打包到dist下的不同目录 rollupOptions: { output: { chunkFileNames: 'static/js/[name]-[hash].js', entryFileNames: 'static/js/[name]-[hash].js', assetFileNames: 'static/[ext]/[name]-[hash].[ext]', }, }, },

 配置vite环境变量

新建三个文件,用来放环境变量,分别对应开发、测试、生产环境,根据需要自行配置

.env.development、.env.test、.env.production

# 区分环境
VITE_APP_ENV=development
# api前缀
VITE_API_BASEURL = /api
# 基础路径前缀
VITE_BASE = ./
# 网页标题
VITE_APP_TITLE  = v3-template

自动按需加载 api & 组件 & 样式

unplugin-auto-import:自动按需引入 vue\vue-router\pinia 等的api

unplugin-vue-components:自动按需引入第三方的组件库组件和我们自定义的组件

 安装

yarn add -D unplugin-vue-components unplugin-auto-import

修改 vite.config.ts

// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

export default {
  plugins: [
    // ...
    AutoImport({
      dts: './src/auto-imports.d.ts',
      imports: ['vue'],
      // Generate corresponding .eslintrc-auto-import.json file.
      // eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
      eslintrc: {
        enabled: true, // Default `false`
        filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
        globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
      },
    }),
    Components({
      dts: './src/components.d.ts',
      // imports 指定组件所在位置,默认为 src/components
      dirs: ['src/components/'],
    }),
  ],
}

修改 .eslintrc.js

// .eslintrc.js

module.exports = { 
  /* ... */
  extends: [
    // ...
    './.eslintrc-auto-import.json',
  ],
}

element-plus

安装

yarn add element-plus

 配置自动按需导入,以下是几个常用插件:

unplugin-auto-import:自动按需引入 vue\vue-router\pinia 等的 api

unplugin-vue-components:自动按需引入 第三方的组件库组件我们自定义的组件

unplugin-icons:可以自动按需引入 所使用的图标,而不用手动 import

vite-plugin-style-import:自动按需引入第三方组件库我们所使用到的 style 样式

安装依赖

yarn add -D unplugin-vue-components unplugin-auto-import

修改 vite.config.ts

// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default {
  plugins: [
    // ...
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    })
  ],
}

启动优化,安装依赖

yarn add -D vite-plugin-optimize-persist vite-plugin-package-config

修改 vite.config.ts

// vite.config.ts
import OptimizationPersist from 'vite-plugin-optimize-persist'
import PkgConfig from 'vite-plugin-package-config'

export default {
  plugins: [
    PkgConfig(),
    OptimizationPersist()
  ]
}

非template组件的自动按需引入样式,以Ant-Design-Vue的message组件为例

<script setup lang="ts">
import { message } from 'ant-design-vue';
message.info('This is a normal message');
</script>

直接使用样式是错乱的,安装vite-plugin-style-import

yarn add -D vite-plugin-style-import

配置vite.config.ts

// vite.config.ts
import styleImport, { AndDesignVueResolve } from 'vite-plugin-style-import';

export default {
  plugins: [
    // ...
    styleImport({
      resolves: [AndDesignVueResolve()],
    }),
  ],
}

 jsx语法支持

安装依赖

yarn add @vitejs/plugin-vue-jsx -D

配置 vite.config.ts

import vueJsx from '@vitejs/plugin-vue-jsx';

export default defineConfig({
  plugins: [...,vueJsx()]
})

 为打包后的文件提供传统浏览器兼容性支持(按需使用)

安装依赖

yarn add @vitejs/plugin-legacy -D

Vite 的默认浏览器支持基线是Native ESM。此插件为不支持本机 ESM 的旧版浏览器提供支持,默认情况下,此插件将:

*为最终包中的每个块生成相应的遗留块,使用@babel/preset-env 转换并作为SystemJS 模块发出(仍然支持代码拆分!)。

*生成一个包含 SystemJS 运行时的 polyfill 块,以及由指定的浏览器目标和包中的实际使用情况确定的任何必要的 polyfill 。

*将<script nomodule>标签注入生成的 HTML 以有条件地仅在没有原生 ESM 支持的浏览器中加载 polyfills 和遗留包。

*注入import.meta.env.LEGACYenv 变量,它只会出现true在旧版生产版本中,以及false在所有其他情况下。

配置vite.config.js

export default defineConfig({
    plugins:[
      legacy({
      targets: ['> 1%, last 1 version, ie >= 11'],
      additionalLegacyPolyfills: ['regenerator-runtime/runtime'], // 面向IE11时需要此插件
    }),
    ]
})

vite-svg-loader

安装依赖

yarn add vite-svg-loader -D

vite.config.ts

import svgLoader from 'vite-svg-loader'

export default defineConfig({
  plugins: [vue(), svgLoader()]
})

使用

import Icon from './assets/icon.svg'
<template>
  <IconOpen />
</template>

 Vue router4

 根据需要自行配置,安装依赖

yarn add vue-router@4

Pinia

Pinia.js 是新一代的状态管理工具,可以认为它是下一代的 Vuex,即 Vuex5.x;它相比于 Vuex 有几个比较明显的变化:

  • 更好的 typescript 支持
  • 移除了 mutations 只留下 actions; actions 支持同步以及异步
  • 无需手动添加 store

 安装依赖

yarn add pinia

 Axios

 安装依赖

yarn add axios

Vueuse

安装依赖

yarn add @vueuse/core

在vite.config.ts中配置自动按需导入

import { VueUseComponentsResolver } from 'unplugin-vue-components/resolvers';

export default defineConfig({
  plugins: [
    AutoImport({
      imports: ['@vueuse/core'],
    }),
    Components({
      resolvers: [VueUseComponentsResolver()],
    }),
  ],
});

 

 

posted @ 2022-02-14 09:13  键盘敲飞  阅读(1455)  评论(3编辑  收藏  举报