vite +vue3 项目搭建
创建项目
npm create vite@latest demo
配置环境变量
vite 提供了开发模式和生产模式
这里我们可以建立 4 个 .env 文件,一个通用配置和三种环境:开发、测试、生产。
env文件中的变量名建议以VITE_APP开头,和vue cli中的VUE_APP相同 ,用法也一致
.env文件 通用配置 用来配置一些公用的,栗子:网页的title
.env.dev文件 开发环境配置 以api url为例 VITE_APP_PROXY_URL=/api
.env.test文件 测试环境配置 以api url为例 VITE_APP_PROXY_URL=/api
.env.prod文件 测试环境配置 以api url为例 VITE_APP_PROXY_URL=/apiProd
配置项目
配置ts导入
找不到模块“./XXX.vue”或其相应的类型声明
在 src 下新建一个vite-env.d.ts
/// <reference types="vite/client" />
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
如果不好使,关闭编辑器再重新打开,如果还不好使,请检查路是否正确
gzip压缩
npm i vite-plugin-compression -D
vite.config.ts
import viteCompression from 'vite-plugin-compression'
viteCompression({
//生成压缩包gz
verbose: true,
disable: false,
threshold: 10240,
algorithm: 'gzip',
ext: '.gz',
})
配置vue-router
1. 安装vue-router
npm install vue-router
2. 安装完后配置vue-router
在src下新建router目录,添加index.ts
// import VueRouter from 'vue-router'
import { createRouter, createWebHashHistory } from 'vue-router'
const routes: any = [
{
path: '/login',
name: 'login',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/login/index.vue')
},
{
path: '/', // 重定向
redirect: (_: any) => {
return { path: '/login' }
},
},
{
path: '/:currentPath(.*)*', // 路由未匹配到,进入这个
redirect: (_: any) => {
return { path: '/404' }
},
},
]
// Vue-router新版本中,需要使用createRouter来创建路由
export default createRouter({
// 指定路由的模式,此处使用的是hash模式
history: createWebHashHistory(),
routes // short for `routes: routes`
})
vuex和pinia二选一
配置vuex
1.安装vuex
npm install vuex
2.安装完后配置vuex
在src下新建store目录,新建index.ts
import { createStore } from 'vuex'
// Vite supports importing multiple modules from the file system using the special import.meta.glob function
// see https://cn.vitejs.dev/guide/features.html#glob-import
const modulesFiles = import.meta.globEager('./modules/*.ts')
const pathList = []
for (const path in modulesFiles) {
pathList.push(path)
}
const modules = pathList.reduce((modules: any, modulePath: any) => {
const moduleName: any = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/, '$1')
const value: any = modulesFiles[modulePath]
modules[moduleName] = value.default
return modules
}, {})
const store = createStore({
modules
})
export default store
配置pinia
安装pinia
npm i pinia
npm i pinia-plugin-persist // 安装持久化存储插件
2.配置
store/modules/user.ts
import { defineStore } from 'pinia'
/**
* useStroe 可以是任意命名
*/
import Cookies from 'js-cookie'
const cookiesStorage: Storage = {
setItem(key, state): any {
console.log(state)
// console.log(state.username)
console.log(key)
let myState = JSON.parse(state)
return Cookies.set(key, myState[key], { expires: 1 / (24 * 60) })
},
getItem(key): string {
return JSON.stringify({
[key]: Cookies.get(key),
})
},
removeItem(key) { },
clear() { },
key(key): any { },
length,
}
export const userStroe = defineStore('main', {
state: () => {
return {
counter: 123,
username: 'bule'
}
},
persist: {
enabled: true,
strategies: [
{
storage: cookiesStorage,
key: 'username',
paths: ['username']
},
{
storage: cookiesStorage,
key: 'counter',
paths: ['counter']
},
],
},
getters: {
double(): number {
return this.counter * 2
}
},
actions: {
getUser() {
this.username = 'bule123'
}
}
})
store/index.ts
import type { App } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
import { userStroe } from './modules/user'
import { departStroe } from './modules/depart'
const store = createPinia()
store.use(piniaPluginPersist)
export function setupStore(app: App<Element>) {
app.use(store)
// 注册pinia状态管理库
registerStore();
}
const appStore: any = {}
export default appStore
export const registerStore = () => {
appStore.userStore = userStroe()
appStore.departStore = departStroe()
}
export { userStroe }
main.ts
import { createApp } from 'vue'
// import './style.css'
import App from './App.vue'
import { setupStore } from './store'
import router from './router'
const app = createApp(App)
setupStore(app)
app.use(router).mount('#app')
配置sass
安装sass
npm i node-sass sass sass-loader -D
vite.config.ts
css: {
preprocessorOptions: {
scss: {
additionalData: `@import "./src/assets/scss/style.scss";@import "./src/assets/scss/index.scss";`,
}
}
}
配置less
安装less
npm i less-loader less -D
vite.config.ts
css: {
preprocessorOptions: {
charset: false,
additionalData: '@import "./src/assets/less/global.less";'
}
}
配置vite.config.ts
配置别名
找不到 path 模块
npm i @types/node
在tsconfig.json中加入
"compilerOptions": {
"types": [
"node"
],
// 用于设置解析非相对模块名称的基本目录,相对模块不会受到baseUrl的影响
"baseUrl": ".",
"paths": {
// 用于设置模块名到基于baseUrl的路径映射
"@/*": [
"src/*"
],
"@assets/*": [
"src/assets/*"
],
"public/*": [
"public/*"
]
}
}
vite.cofig.ts
import { resolve } from 'path'
resolve: {
alias: {
//路径别名
"@": resolve(__dirname, "./src"),
"@assets": resolve(__dirname, "./src/assets"),
"public": resolve(__dirname, "./public"),
},
extensions: ['.js', '.json', '.ts', '.vue'], // 使用路径别名时想要省略的后缀名,可以自己 增减
},
antd
npm i ant-design-vue -S
npm i unplugin-vue-components -D //用于按需引入
vite.config.js
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
plugins:[
Components({
resolvers: [
AntDesignVueResolver({
importStyle: 'less', // 一定要开启这个配置项
}),
],
}),
]
主题色
css: {
preprocessorOptions: {
charset: false,
additionalData: '@import "./src/assets/less/global.less";',
less: {
modifyVars: {
"primary-color": "#1DA57A",
"link-color": "red"
},
javascriptEnabled: true
}
},
}
element-plus
npm i element-plus -S
npm i unplugin-vue-components -D //用于按需引入
npm i unplugin-auto-import
vite.config.js
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
plugins:[
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver({ importStyle: "sass", }), ],
}),
],
css: {
preprocessorOptions: {
scss: {
additionalData: `@use "./src/assets/scss/style.scss";@use "./src/assets/scss/index.scss";@use "./src/assets/scss/element-theme.scss";`,
}
}
},
src/assets/scss/element-theme.scss
@forward "element-plus/theme-chalk/src/common/var.scss" with (
$colors: (
"primary": (
"base": #3F9A12,
),
"success": (
"base": #67C23A,
),
"warning": (
"base": #E6A23C,
),
"danger": (
"base": #F56C6C,
),
"error": (
"base": #F56C6C,
),
"info": (
"base": #909399,
),
),
$button-padding-horizontal: (
"default": 80px
)
);