跳到主要内容

vite3

前言

Vite 不再支持 Node 12/13/15,因为上述版本已经进入了 EOL 阶段,须使用 Node 14.18+/16+ 版本

创建项目

预设的模版

pnpm create vite 项目名称
pnpm create vite 项目名称 --template vue
pnpm create vite 项目名称 --template vue-ts

### 创建一个 vite3-app 的项目

```bash
yarn create vite vite3-app --template vue
cd vite3-app
yarn

# 查看 vite 有哪些命令
npx vite --help

初始项目目录结构

vite3-app1
├── README.md
├── index.html
├── package.json
├── public
| └── vite.svg
├── src
| ├── App.vue
| ├── assets
| | └── vue.svg
| ├── components
| | └── HelloWorld.vue
| ├── main.js
| └── style.css
├── vite.config.js
└── yarn.lock

npx vite --help 打印的日志

vite/3.2.4

Usage:
$ vite [root]

Commands:
[root] start dev server
build [root] build for production
optimize [root] pre-bundle dependencies
preview [root] locally preview production build

For more info, run any command with the `--help` flag:
$ vite --help
$ vite build --help
$ vite optimize --help
$ vite preview --help

Options:
--host [host] [string] specify hostname
--port <port> [number] specify port
--https [boolean] use TLS + HTTP/2
--open [path] [boolean | string] open browser on startup
--cors [boolean] enable CORS
--strictPort [boolean] exit if specified port is already in use
--force [boolean] force the optimizer to ignore the cache and re-bundle
-c, --config <file> [string] use specified config file
--base <path> [string] public base path (default: /)
-l, --logLevel <level> [string] info | warn | error | silent
--clearScreen [boolean] allow/disable clear screen when logging
-d, --debug [feat] [string | boolean] show debug logs
-f, --filter <filter> [string] filter debug logs
-m, --mode <mode> [string] set env mode
-h, --help Display this message
-v, --version Display version number

vite 配置

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

// 这种写法不支持 **Dynamic require of "path" is not supported**
// 不支持持 commonJS
// const path = require('path')
// const resolveDir = dir => path.resolve(__dirname, dir)

// import path from 'path'
// const resolveDir = dir => path.resolve(__dirname, dir)

import { resolve } from 'path'
const resolveDir = dir => resolve(__dirname, dir)

// 写法一
export default defineConfig({
base: '/',
publicDir: 'public',
resolve: {},
plugins: [vuePlugin()]
...
})

// 写法二
export default defineConfig((config) => {
// config: { mode: 'development', command: 'serve', ssrBuild: false }
const { mode } = config
return {
base: mode === 'development' ? '/' : './',
publicDir: 'public',
resolve: {},
server: {},
css: {},
build: {},
plugins: [vuePlugin()]
}
})

// 写法三
export default defineConfig({ mode, command, ssrBuild } => {
return {
base: mode === 'development' ? '/' : './',
publicDir: 'public',
resolve: {},
server: {},
css: {},
build: {},
plugins: [vuePlugin()]
}
})

下面进行简单配置

import VuePlugin from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig } from 'vite'
const resolveDir = dir => resolve(__dirname, dir)

export default defineConfig(({ mode }) => {
/**
* config 参数
* { mode: 'development', command: 'serve', ssrBuild: false }
*/
return {
// 基础路径,线上环境可能是,如:/test/h5/,如果将 .js .css等资源文件存放 oss 配置为 oss 的路径
base: mode === 'development' ? '/' : './',
// 静态目录
publicDir: 'public',
// 资源目录
assetsDir: 'assets',
resolve: {
// 配置别名,写法一
alias: {
'@': resolve('./src'),
'@components': resolve('./src/components'),
'@styles': resolve('./src/styles')
},
// 配置别名,写法二
alias: [{
find: '@',
replacement: resolveDir('./src')
}, {
find: '@components',
replacement: resolveDir('./src/components')
}, {
find: '@styles',
replacement: resolveDir('./src/styles')
}]
},
// css 配置项
css: {
preprocessorOptions: {
scss: {
additionalData: `@import '@/styles/variable.scss';`
}
}
},
// 服务配置
server: {
// 如果指定端口已被使用,vite 将退出
strictPort: true,
// 是否自动打开浏览器
open: true,
// 如果需要局域网访问,配置成 '0.0.0.0' yarn dev 时会显示 局域网的访问地址
host: '0.0.0.0',
// 端口
port: 9000,
// 是否开启 https
https: false,
// 是否允许跨域
cors: true,
headers: {
'api': '2.0'
},
// 代理
proxy: {
'/news': 'http://xxx.com/reg/api/news',
'/api': {
target: 'http://xxx.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '/reg/api')
}
}
},
build: {
target: 'es2015',
outDir: 'dist',
assetsDir: 'assets',
cssCodeSplit: true,
minify: 'terser',
sourcemap: false
},
// 插件
plugins: [VuePlugin()]
}
})

剔除注释后的配置

import VuePlugin from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig } from 'vite'
const resolveDir = dir => resolve(__dirname, dir)

export default defineConfig(({ mode }) => {
return {
base: mode === 'development' ? '/' : './',
publicDir: 'public',
assetsDir: 'assets',
resolve: {
alias: {
'@': resolve('./src'),
'@components': resolve('./src/components'),
'@styles': resolve('./src/styles')
}
},
css: {
preprocessorOptions: {
scss: {
additionalData: `@import '@/styles/variable.scss';`
}
}
},
server: {
strictPort: true,
open: true,
host: '0.0.0.0',
port: 9000,
https: false,
cors: true,
headers: {
'api': '2.0'
},
proxy: {
'/news': 'http://xxx.com/reg/api/news',
'/api': {
target: 'http://xxx.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '/reg/api')
}
}
},
build: {
target: 'es2015',
outDir: 'dist',
assetsDir: 'assets',
cssCodeSplit: true,
minify: 'terser',
sourcemap: false
},
// 插件
plugins: [VuePlugin()]
}
})

生成 jsconfig.json

# 项目根目录执行
npx jsconfig.json -t 'vuejs'
{
"compilerOptions": {
"checkJs": false,
"resolveJsonModule": true,
"moduleResolution": "node",
"target": "es2020",
"module": "es2015",
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
}
},
"exclude": [
"dist",
"node_modules",
"build",
".vscode",
".nuxt",
"coverage",
".npm",
".yarn"
],
"typeAcquisition": {
"enable": true
}
}

对比 @vue/cli 创建项目生成的 jsconfig.json

// @vue/cli 创建项目生成的 
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./",
"moduleResolution": "node",
"paths": {
"@/*": [
"src/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}

代码规范

代码规范,采用 editorconfig + eslint + prttier + husky + lintstag

配置 editorconfig

在项目根目录,新建 .editorconfig

root = true // 最顶级的配置,相当于根 editorconfig 直到查找到 root=true 才会停止查找不然会一直向上查找

[*] // 通配符匹配 任意字符串的文件
charset = utf-8 // 编码格式
indent_style = space
indent_size = 2
end_of_line = lf // 定义换行符: lf | cr | crlf
insert_final_newline = true // 设为 true 表明使文件以一个空白行结尾, false 反之
trim_trailing_whitespace = true // 设为 true 表示会除去换行行首的任意空白字符,false 反之
max_line_length = 80

[*.md] // 通配符匹配 .md 的文件
trim_trailing_whitespace = false
max_line_length = 0

剔除注释后的配置

root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
max_line_length = 80

[*.md]
trim_trailing_whitespace = false
max_line_length = 0

配置 eslint 和 prettier

  • eslint 配置代码风格、质量的校验
  • prettier 用于代码格式的校验
  • eslint-config-prettier 使用 prettier 默认推荐配置,关闭 eslint 自身的格式化功能,防止 prettier 和 eslint 的自动格式化冲突
  • eslint-plugin-prettier eslint 插件, 由 Prettier 生态提供,用于报告错误给 ESLint
  • eslint-plugin-vue vue 专门的 eslint 规则插件,用于检查 .vue 文件
  • @babel/core
  • @babel/eslint-parser eslint 的 babel 解析器代替 babel-eslint
yarn add eslint eslint-config-prettier eslint-plugin-prettier eslint-plugin-vue prettier @babel/core @babel/eslint-parser -D

在项目根目录,新建 .eslintrc.js

配置代码 pre-commit

使用 husky + lintstag

添加 vue-router

项目添加 vue-router4 插件,src 下新建 router 目录和 index.js ,src 下 新建 views 目录,并新建 Home.vue 和 About.vue(内容写点)

yarn add vue-router@latest -S
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
history: createWebHashHistory(),
scrollBehavior() {
return {
el: '#app',
top: 0,
behavior: 'smooth'
}
},
routes: [{
path: '/',
name: 'home',
component: () => import('@/views/Home.vue')
}, {
path: '/about',
name: 'about',
component: () => import('@/views/About.vue')
}]
})

export default router

将原先 App.vue 的内容移动 Home.vue 中,