前言:
直接安装下面几个依赖 @types/node后面要使用 vue2版本建议2.7以上
node -v: v16.17.1
npm -v: 9.4.0
"dependencies": {
"vue": "2.7.10",
},
"devDependencies": {
"@types/node": "^20.4.7",
"@vitejs/plugin-vue2": "^2.2.0",
"vite": "^4.4.8"
}
1.vite.config.js配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
export default defineConfig({
plugins: [
vue(),
]
})
2.导入时省略文件类型后缀
我们在导入 vue、js 等文件时往往喜欢省略类型后缀,这需要配置 extensions
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
export default defineConfig({
plugins: [
vue(),
],
resolve: {
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
},
})
3.配置路径别名
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
export default defineConfig({
plugins: [
vue(),
],
resolve: {
alias: {
'@': resolve('src'),
},
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
},
})
4.环境变量 vite环境变量地址
.env.development // 开发环境
.env.dev // 测试环境
.env.production // 线上环境
5.package.json设置启动命令
"serve:dev": "vite --mode dev",
"serve:beta": "vite --mode beta",
"serve:prod": "vite --mode prod",
"build:dev": "vite build --mode dev",
"build:beta": "vite build --mode beta",
"build:prod": "vite build --mode prod",
6.本地启动不同环境
开发环境:pnpm serve:dev
测试环境:pnpm serve:beta
生产环境:pnpm serve:prod
报错问题汇总
1. pathToRegexp引入出错
Uncaught SyntaxError: The requested module '/node_modules/.vite/deps/path-to-regexp.js?v=ba8728b6' does not provide an export named 'default' (at index.vue:19:1)
解决方法:
import pathToRegexp from 'path-to-regexp'
替换
import * as pathToRegexp from 'path-to-regexp'
2.import.meta.glob替换require.context vite官网指南
const modulesFiles = require.context('./modules', true, /\.js$/)
替换
const modulesFiles = import.meta.glob('./modules/*.js')
- import.meta.glob('./modules/*.js',{ eager: true }) 加上第二个参数直接导入,不加默认异步导入
2.导入文件夹下所有.vue 文件 加上第二个参数{ eager: true }直接导入:
const allComponents = import.meta.glob('./components/*/*.vue',{ eager: true })
const res_components = {}
Object.entries(allComponents).forEach(([path, Module]) => {
const name = Module.default.name
res_components[name] = Module.default
})
export default {
components: { ...res_components },
}
3 导入文件夹下所有.js 文件 以导入store为例:
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)
const modulesFiles = import.meta.glob('./modules/*.js',{ eager: true })
const modules = Object.entries(modulesFiles).reduce((modules, [path, Module]) => {
const moduleName = path.slice(10,-3)
modules[moduleName] = Module.default
return modules
}, {})
const store = new Vuex.Store({
modules,
getters
})
export default store
store结构如下:
3.图片引入问题
logo: require('@/assets/images/xiaoxiang_logo.png')
替换
import logo from '@/assets/images/xiaoxiang_logo.png'
4.icons svg目录引入处理
- 安装依赖插件 vite-plugin-svg-icons
yarn add vite-plugin-svg-icons
- 安装 fast-glob
yarn add fast-glob
- 配置 vite.config.js
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [resolve(__dirname, 'src/icons/svg')],
symbolId: 'icon-[name]'
}),
],
resolve: {
alias: {
'@': resolve('src'),
},
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'],
},
})
4. 在 main.js入口注册脚本
import 'virtual:svg-icons-register'
注意: vite-plugin-svg-icons 插件注册,不引入会导致svg图标无法正常显示
5. 封装 SvgIcon 组件
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
import { isExternal } from '@/utils/validate'
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return isExternal(this.iconClass)
},
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
6. main.js 注册组件
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'
Vue.component('svg-icon', SvgIcon)
7.页面使用
<svg-icon icon-class="bug" />
5. vite无法使用node的模块 要使用第三方插件 :vite官网提示地址
通过polyfill解决方法:
- 安装依赖
yarn add @esbuild-plugins/node-globals-polyfill
yarn add @esbuild-plugins/node-modules-polyfill
2.vite.config.js的配置如下
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [resolve(__dirname, 'src/icons/svg')],
symbolId: 'icon-[name]'
})
],
resolve: {
alias: {
'@': resolve('src'),
path: 'rollup-plugin-node-polyfills/polyfills/path'
},
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
}
})
3.现在就可以在组件中导入使用了
import { resolve } from 'path'
resolve(basePath, router.path)
4.path.resolve简易替代品
// 解析文件路径。类似于path.resolve
export const pathResolve = (...paths) => {
let resolvePath = ''
let isAbsolutePath = false
for (let i = paths.length - 1; i > -1; i--) {
const path = paths[i]
if (isAbsolutePath) {
break
}
if (!path) {
continue
}
resolvePath = path + '/' + resolvePath
isAbsolutePath = path.charCodeAt(0) === 47
}
if (/^\/+$/.test(resolvePath)) {
resolvePath = resolvePath.replace(/(\/+)/, '/')
} else {
resolvePath = resolvePath.replace(/(?!^)\w+\/+\.{2}\//g, '')
.replace(/(?!^)\.\//g, '')
.replace(/\/+$/, '')
}
return resolvePath
}
6.css sass 相关问题
1.vite.config.js配置全局加载scss
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
export default defineConfig({
plugins: [
vue(),
createSvgIconsPlugin({
iconDirs: [resolve(__dirname, 'src/icons/svg')],
symbolId: 'icon-[name]'
})
],
resolve: {
alias: {
'@': resolve('src'),
path: 'rollup-plugin-node-polyfills/polyfills/path'
},
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
},
css: {
loaderOptions: {
sass: {
prependData: `
@/styles/variables.scss"; // scss文件地址
`
}
}
}
})
2.CSS modules使用 vite官网CSS Modules地址
variables.module.scss
$menuText:#B4B9C8;
$menuActiveText:#fff;
:export {
menuText: $menuText;
menuActiveText: $menuActiveText;
}
slider.vue使用
<template>
<el-menu
:default-active="activeMenu"
:collapse="isCollapse"
:background-color="variables.menuBg"
:text-color="variables.menuText"
:unique-opened="true"
:active-text-color="variables.menuActiveText"
:collapse-transition="false"
mode="vertical"
>
...
</el-menu>
</template>
<script>
import variables from "@/styles/variables.module.scss";
export default {
computed: {
variables() {
return variables;
},
},
};
</script>
7.jsx文件配置
1.yarn add @vitejs/plugin-vue2-jsx -D
2.vite.config.js配置
import { resolve } from 'path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
import vueJsx from '@vitejs/plugin-vue2-jsx'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [
vue(),
vueJsx(),
createSvgIconsPlugin({
iconDirs: [resolve(__dirname, 'src/icons/svg')],
symbolId: 'icon-[name]'
})
],
resolve: {
alias: {
'@': resolve('src'),
path: 'rollup-plugin-node-polyfills/polyfills/path'
},
extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
},
esbuild: {
jsxFactory: 'h',
jsxFragment: 'Fragment'
},
css: {
loaderOptions: {
sass: {
prependData: `
@/styles/variables.scss"; // scss文件地址
`
}
}
}
})
- jsx文件支持模式@vitejs/plugin-vue2-jsx GitHub地址
import { defineComponent } from 'vue'
// named exports w/ variable declaration: ok
export const Foo = defineComponent({})
// named exports referencing variable declaration: ok
const Bar = defineComponent({ render() { return <div>Test</div> }})
export { Bar }
// default export call: ok
export default defineComponent({ render() { return <div>Test</div> }})
// default export referencing variable declaration: ok
const Baz = defineComponent({ render() { return <div>Test</div> }})
export default Baz
不支持模式
// not using `defineComponent` call
export const Bar = { ... }
// not exported
const Foo = defineComponent(...)
##8.配置autoprefixer自动添加前缀
yarn add autoprefixer -D
css: {
postcss: {
plugins: [
autoprefixer({
overrideBrowserslist: [
'Android 4.1',
'iOS 7.1',
'Chrome > 31',
'ff > 31',
'ie >= 8'
// 'last 2 versions', // 所有主流浏览器最近2个版本
]
})
]
}
}
eslint 配置
1.依赖安装
yarn add eslint eslint-plugin-vue vite-plugin-eslint -D
2.vite.config.js配置
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
import eslintPlugin from 'vite-plugin-eslint'
export default defineConfig({
plugins: [
vue(),
eslintPlugin({
include: ['src/**/*.js', 'src/**/*.vue', 'src/*.js', 'src/*.vue']
})
]
})
3.在项目根目录下新建.eslintrc.cjs
module.exports = {
root: true,
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
node: true,
es6: true
},
extends: ['plugin:vue/recommended', 'eslint:recommended'],
// 规则参考 https://eslint.nodejs.cn/docs/latest/rules/
rules: {
}
}
1.rules相关配置参考官方文档 规则参考 2.如果你是新建的.eslintrc.js以.js后缀的会报如下错误,把后缀改为.cjs结尾就好了
vite/node_modules/.pnpm/@eslint+eslintrc@2.1.1/node_modules/@eslint/eslintrc/dist/eslintrc.cjs not supported.
.eslintrc.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename .eslintrc.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /Users/suesea/company/xiaoxiang/practice/vite/seller-admin-vite/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
4.vscode 安装eslint插件
1.在vscode设置中点击settings
2.切换到User,上面搜索eslint,随便点个蓝色字体的Edit in settings.json 进入设置页面
3.添加配置,看红框标出的,其他不用管,这一步是为了让vscode的eslint插件在你点击control + s 保存时帮你修复错误
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
4.项目package.json可以加上一条修改eslint错误的命令
"lint": "eslint --fix --ext .js,.vue src",
项目迁移时eslint报错太多,运行这个命令可以修复一部分,修复时要注意,修复完成后文件格式可能和之前不一致,这是配置的.eslintrc.cjs和未迁移之前不同导致的。只能对比修改,看看不影响逻辑就行。
5.总结 1.vscode 安装的eslint插件会会去找项目中安装的eslit来运行,找不到就会去找全局的
"devDependencies": {
"eslint": "^8.46.0",
}
2.一般情况下配置好.eslintrc.cjs,后缀要正确,页面如果有错误的,vscode的eslint插件就会给你标红 3.一般的小错误eslint会帮你修复,如果时规则导致的就需要你去关闭相应的规则 规则参考
'no-async-promise-executor': 'off', // 禁止使用异步函数作为 Promise 执行器
'no-prototype-builtins': 'off', // 禁止直接在对象上调用某些 Object.prototype 方法
'vue/multi-word-component-names': 'off', // 关闭eslint检查文件名是否为驼峰命名
'vue/first-attribute-linebreak': [2, {
// 单行时,第一属性前不允许使用换行符
'singleline': 'beside',
// 多行时,第一属性前必须使用换行符
'multiline': 'below'
}],
vue/multi-word-component-names
vue/first-attribute-linebreak
这两个是eslint-plugin-vue中的,参考连接