vite构建
从构建工具开始,vite。据说牛逼哄哄的,我来了
看官网首先建立一个vite的项目
npm init vite@latest
它会让我们按照提示创建项目
- project name 我们的项目名称
- select a framework 选择框架
√ Project name: ... vue3-backstage
√ Select a framework: » vue
√ Select a variant: » vue-ts
Done. Now run:
cd vue3-backstage
npm install
npm run dev
下载所以依赖,允许项目
目前项目结构
项目要使用到路由和状态管理 所以下载vue-router和替代了vuex的pinia
改造下vite.config.ts
导出来的配置文件更改为情景配置,根据我们打包环境进行配置。这样子defineConfig就不是一个对象了,而是一个函数。函数里面返回一个配置项
import { defineConfig, ConfigEnv, loadEnv } from 'vite'
import { resolve } from 'path';
import vue from '@vitejs/plugin-vue'
const pathResolve = (dir: string): any => {
return resolve(__dirname, '.', dir);
};
const alias: Record<string, string> = {
'@': pathResolve('./src/')
};
// mode是函数的参数,里面包含两个属性
// 1. mode 环境的变量,development production
// 2. command 值为serve是开发环境 值为build是生成环境
export default defineConfig((mode: ConfigEnv) => {
// 获取到env.xxx文件中定义的字段 mode.mode提示是哪种环境下
const env = loadEnv(mode.mode, process.cwd())
return {
plugins: [vue()], // 需要用到的插件数组
resolve: { alias } // 文件系统路径的别名
}
})
在你配置路径别名的时候,需要你在tsconfig.json中对应的添加
"baseUrl": ".",
"paths": {
"@*": ["src/*"]
},
项目添加pinia
项目添加pinia。在src文件中创建stores文件夹,在文件夹中创建两个index.ts文件和modules文件夹
在index.ts文件中创建pinia对象并且导出
import { createPinia } from "pinia";
const pinia = createPinia()
export default pinia
然后在main.ts中使用pinia
import { createApp } from 'vue'
import App from './App.vue'
import pinia from '@/stores/index'
const app = createApp(App)
app.use(pinia)
app.mount('#app')
这样子我们就可以愉快的使用pinia了。pinia怎么使用可以看它的中文文档 上手很快,果然比vuex好用
项目使用vue-router
接下来让项目可以使用vue-router路由
在src目录下面创建router文件夹,在里面创建index.ts。在这个文件里面创建router对象,并且将所有的路由都导入到这个文件里面进行处理
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
// 将modules里面的所有路由文件导入出来
const metaRouters = import.meta.globEager("./modules/*.ts");
console.log(metaRouters)
// 在进行处理,将文件里面的内容提取出来保存到路由数组里面
export const routerArray: RouteRecordRaw[] = [];
Object.keys(metaRouters).forEach(item => {
Object.keys(metaRouters[item]).forEach((key: any) => {
console.log(metaRouters[item][key])
routerArray.push(...metaRouters[item][key]);
});
});
const routes: RouteRecordRaw[] = [
{
path: "/login",
name: "login",
component: () => import("@/views/login/index.vue"),
meta: {
title: "登录页",
}
},
...routerArray
]
const router = createRouter({
history: createWebHashHistory(),
routes,
scrollBehavior: () => ({ left: 0, top: 0 })
});
export default router
然后在main.ts中使用app.use(router) 这样子我们就可以愉快的使用了
element-plus
接下来就是组件了,当然是使用大名鼎鼎的element-plus好用顶呱呱
这里使用的是直接全部导入的,分包有很多坑。后期优化直接使用cdn进行优化 在main.ts文件中进行导入
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)
顺便将element的icon都导入,element-plus需要下载专门的包进行导入 先下载npm i @element-plus/icons-vue 这个包 然后在main.ts中写入
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
一天结束