vite中文文档:https://cn.vitejs.dev
创建项目(node版本12以上)
npm init @vitejs/app 项目名 (注意:npm init vite-app xxx是vite1.0)
选择vue
如果使用typescript,选择vue-ts
创建完成
目录如下:
增加别名
修改vite.config.js文件
import { resolve } from "path";
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "src")
}
}
})
使用:import HelloWorld from "@/components/HelloWorld .vue";
区分开发环境和生产环境(如接口调用时不同url)
默认:执行vite 时是 development 开发模式,vite build时是 production 生产模式
- 在项目根目录下新建文件:(不同模式下获取变量对应的不同的值)
.env.development
VITE_APP_TITLE='开发环境'
VITE_APP_BASE_URL='/'
.env.production
VITE_APP_TITLE='生产环境'
VITE_APP_BASE_URL='/api'
自定义环境变量命名规范:必须以VITE_
为前缀
- 可以为自定义变量增加TypeScript类型定义,src目录下env.d.ts文件中增加:
interface ImportMetaEnv {
VITE_APP_TITLE: string,
VITE_APP_BASE_URL: string
}
- 通常还会有测试环境test等其他自定义模式,例如
修改package.json文件中scripts,指定模式:
"scripts": {
"dev": "vite",
"test": "rimraf ./test && vue-tsc --noEmit && vite build --mode test",
"build": "rimraf ./dist && vue-tsc --noEmit && vite build --mode production",
"serve": "vite preview"
}
修改vite.config.js:
export default defineConfig(({ command, mode }) => {
return {
build: {
outDir: mode === "production" ? "dist" : "test"
}
}
})
(npm install rimraf --save-dev,删除指定文件夹)
按需引入element-plus组件及其样式
安装依赖:
npm install element-plus --save
npm install vite-plugin-components vite-plugin-style-import --save-dev
1.修改vite.config.js:
import ViteComponents, { ElementPlusResolver } from 'vite-plugin-components'
import styleImport from 'vite-plugin-style-import';
export default defineConfig(({ command, mode }) => {
return {
plugins: [
vue(),
//按需引入element-plus组件
ViteComponents({
customComponentResolvers: [ElementPlusResolver()],
}),
//按需引入element-plus组件样式
styleImport({
libs: [{
libraryName: 'element-plus',
esModule: true,
resolveStyle: (name) => {
return `element-plus/theme-chalk/${name}.css`;
}
}]
})]
}
})
- 直接使用element-plus的组件,无需其他修改
<el-button type="warning" icon="el-icon-close" circle></el-button>
- build时tslint报错:
Cannot find module 'element-plus/es/popper' or its corresponding type declarations...
解决:忽略node_modules检查
package.json -> scripts -> build,添加--skipLibCheck
"build": "rimraf ./dist && vue-tsc --noEmit --skipLibCheck && vite build"
或者,tsconfig.json -> compilerOptions -> 添加 skipLibCheck: true
"compilerOptions": {
"skipLibCheck": true
}
使用scss
安装依赖:
npm install sass --save-dev
- vite.config.js文件里增加css: {...},可配置公共样式和全局变量:
export default defineConfig({
css: {
preprocessorOptions: {
scss: {
additionalData: '@import "./src/assets/index.scss";' // 此处为字符串加分号;,多个文件分号分割
}
}
}
})
- index.scss,变量$color,和css类选择器样式color
$color: green;
.color {
color: red;
}
- 使用变量和样式,文字为绿色
<template>
<div>
...
<h4 class="color">2.方法</h4>
...
</div>
</template>
<style lang="scss" scoped>
.color {
color: $color;
}
</style>
路由vue-router
安装vue-router 4.x版本:
npm install vue-router@next --save
- src目录下新建文件夹router,router文件夹下新建文件index.ts
import { RouteRecordRaw, createRouter, createWebHashHistory } from "vue-router";
const routes: RouteRecordRaw[] = [
{path: "/", redirect: "/home"},
{
path: "/home",
name: "Home",
component: () => import("@/views/index.vue"),
},
{
path: "/logo",
name: "Logo",
component: () => import("@/views/Logo.vue"),
},
];
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
- 修改main.ts
import router from "./router/index"
createApp(App).use(router).mount('#app')
vuex 4.x
安装依赖:
npm install vuex@next --save
-
src目录下新建store文件夹,store文件夹下新建modules文件夹和index.ts文件
举个栗子:title.ts,写法和vue2无差别
import {getAxios} from "@/utils/request";
const title = {
namespaced: true,
state: {
titles: []
},
mutations: {
showTitle(state, action){
state.titles = action.payload
}
},
actions: {
showTitle({commit}){
return new Promise((resolve, reject) => {
getAxios('/json/article-list.json').then(resp => {
let action = {
type: 'showTitle',
payload: resp
}
commit(action)
resolve()
}).catch(err => {
console.log(err)
reject()
})
})
}
},
getters: {
getTitle(state){
return state.titles.map((item: {title: string}) => item.title).join(",")
}
}
}
export default title
modules/index.ts
import user from "@/store/modules/user";
import title from "@/store/modules/title";
export default {
user,
title
}
- 创建store
index.ts:
import { createStore } from "vuex";
import modules from "./modules";
const store = createStore({
modules
})
export default store
main.ts:
import {createApp} from 'vue'
import App from './App.vue'
import router from "@/router"
import store from "@/store";
const app = createApp(App)
app.use(router).use(store).mount('#app')
- 使用
import {ref} from 'vue'
import {useStore} from "vuex";
export default {
name: 'demo',
setup() {
const store = useStore();
const title = ref("");
const showTitle = () => {
store.dispatch('title/showTitle').then(() => {
title.value = store.getters["title/getTitle"];
});
}
return {
title,
showTitle
}
}
axios及vite配置代码解决开发环境跨域问题
安装依赖:
npm install axios --save
封装axios get、post请求方法,不同环境不同baseURL:
import axios from "axios";
//显示、隐藏loading加载中
let httpRequestCount: number = 0;
let loading: any = null;
export const showLoading = () => {
if (httpRequestCount === 0) {
// 显示loading
}
httpRequestCount++;
}
const hideLoading = () => {
httpRequestCount--;
if (httpRequestCount === 0) {
loading.close();
}
}
//axios拦截器数据处理
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASE_URL,
timeout: 15000
});
service.interceptors.request.use(
config => {
showLoading();
config.headers.token = "123";
return config
},
error => {
hideLoading();
return Promise.reject(error);
}
);
service.interceptors.response.use(
response => {
hideLoading();
const {code, data, msg} = response.data;
if(code === 200) {
return Promise.resolve(data);
}else {
// 提示错误信息
return Promise.reject(data);
}
},
error => {
hideLoading();
// 提示错误信息
return Promise.reject(error);
}
);
export const getAxios = (url: string, params: object | null = {}, option: object | null = {}) => {
return service({
url,
params,
method: "get",
...option
})
}
export const postAxios = (url: string, params: object | null = {}, option: object | null = {}) => {
return service({
url,
params,
method: "post",
...option
})
}
修改vite.config.js
export default defineConfig(({ command, mode }) => {
return {
server: {
proxy: {
'/api': {
target: 'http://xxx.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
}
}
}
})