使用Vue3.2+Vite+ts+element-puls+pinia搭建前端项目
一、package.json
{
"name": "vue-main-web",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite --mode dev",
"build": "vue-tsc --noEmit && vite build --mode production",
"preview": "vite preview"
},
"dependencies": {
"element-plus": "^2.0.5",
"normalize.css": "^8.0.1",
"pinia": "^2.0.11",
"pinia-plugin-persist": "^1.0.0",
"vue": "^3.2.25",
"vue-router": "^4.0.13"
},
"devDependencies": {
"@types/node": "^17.0.21",
"@vitejs/plugin-vue": "^2.2.0",
"less": "^4.1.2",
"minimist": "^1.2.5",
"sass": "^1.49.9",
"sass-loader": "^12.6.0",
"typescript": "^4.5.4",
"vite": "^2.8.0",
"vue-tsc": "^0.29.8"
}
}
二、main.ts
import "normalize.css"
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
import Router from './router/router'
import store from './store'
const app = createApp(App)
app.use(ElementPlus)
app.use(Router)
app.use(store)
app.mount('#app')
三、vite.config.ts
使用minimist获取命令行
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path')
const modeEnv = require('minimist')(process.argv.slice(2)).env
switch (modeEnv) {
case 'dev':
console.log('开发环境')
break;
case 'test':
console.log('测试环境')
break;
case 'production':
console.log('生产环境')
break;
}
const baseMap = {
dev: './',
test: '',
production: '',
}
export default defineConfig({
base: (baseMap as any)[modeEnv] || '',
resolve: {
alias: {
'@': path.resolve(__dirname,'./src'),
}
},
build: {
terserOptions: {
compress: {
drop_console: modeEnv === 'production' ? true : false
}
}
},
server: {
host: '0.0.0.0',
port: 8888,
hmr: {
overlay: true
},
proxy: {
'/api': {
target: 'http://xxx',
changeOrigin: true,
},
}
},
plugins: [vue()]
})
四、env.d.ts
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
interface ImportMetaEnv {
VITE_APP_BASE: string;
VITE_APP_ENV: string;
}
五、pinia入口及使用
- 入口
import {createPinia} from "pinia";
import piniaPluginPersist from "pinia-plugin-persist";
const store = createPinia()
store.use(piniaPluginPersist)
export default store
- 使用 user.ts
import {defineStore} from 'pinia'
export const useUserStore = defineStore(
"main_user_info",
{
state: () => {
return {
name: '张三',
age: 12
}
},
actions: {
changeName () {
this.age++
}
},
persist: {
enabled: true
}
}
)
|