前言
本项目采用的是Vite + Vue3 + ts + less 的开发技术
组件或页面统一使用 单文件组件 <script setup>
搭建项目
npm init vue@latest
根据官网例子Cypress 这个包没有安装下来。项目中移除这个包就安装成功,启动项目Go
由于项目是新建的所以内部的一些初始化文件是不需要的可以删除并修改,如App内部的文件
修改完成后,开始增加我们的路由文件
创建路由文件,个人习惯按模块区分路由,方便查找定位
// import type 是干嘛的
// home 路由书写完毕,其他的路由也是相同的
import type {RouteRecordRaw} from "vue-router";
const home: Array<RouteRecordRaw> = [
{
path: '/home',
name:'Home',
meta:{},
component: () => import('@/pages/home/home.vue')
}
]
export default home
// --------------------------分隔符--------------------------------
import type {RouteRecordRaw} from "vue-router";
import {createRouter, createWebHistory} from 'vue-router'
// import HomeRouter from './module/home'
// 问题:如果页面较多,每个都需要这路由入口引入,写起来改动的文件多,涉及合并代码冲突
// 万一忘记引入,Vite是否有自动引入或者读取文件的操作
// 查询资料
// Vite 支持使用特殊的 import.meta.glob 和 import.meta.globEager 函数从文件系统导入多个模块
// glob 方法返回一个函数,函数执行结果为 promise.需要then export default 的返回值
// globEager 返回hanshu export default 的返回值
const modulesSync = import.meta.globEager('./module/*.ts', {import: 'default'})
// 返回一个对象 key为获取到的文件路径,value 为一个动态执行的函数
// 执行函数为一个 promise 的函数,返回值就是文件内部的执行结果
const modulesAsync = import.meta.glob('./module/*.ts', {import: 'default'})
let routes: Array<RouteRecordRaw> = []
// 异步导入
async function getRouterAsync() {
return new Promise(resolve => {
Promise.all(Object.keys(modulesAsync).map((path: string) => {
return modulesAsync[path]()
})).then(res => {
res.forEach((item: any) => {
routes = routes.concat(item)
})
resolve('success')
})
})
}
// 同步导入
function getRouterSync() {
Object.keys(modulesSync).forEach((path: string) => {
const routerInfo: any = modulesSync[path]
routes = routes.concat(routerInfo)
})
}
await getRouterAsync()
console.log(routes)
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes
})
console.log(router)
export default router
路由的基建已经搭建完毕
新问题:import type {RouteRecordRaw} from "vue-router"是干嘛的?为啥需要这么写。
接下来选择css框架
个人选择的是less和tailwindcss快速构建页面和组件
- 安装Tailwindcss(由于 Tailwind 不会自动添加浏览器引擎前缀到生成的 CSS 中,我们建议您安装 autoprefixer 去处理这个问题,就像下面的代码片段所展示的那样。)
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
- 支持直接将 CSS 文件导入到 JS 中,那么您也可以完全跳过创建 CSS 文件,而直接导入 tailwindcss / tailwind.css
// app.js 或者 app.ts 或者 main.ts
import "tailwindcss/tailwind.css"
- 配置 tailwindwebstrom编辑器无提示解决办法
npx tailwindcss init
这时文件根目录会增加一个 tailwind.config.js 文件详细的配置文档
- 引入文件开始使用
总结
- 今天解决tailwindcss无提示解决了好久,换了包成功了。
- glob 和 globEager 之前使用 glob 获取。由于是异步的导致路由时有时无。
import和import type都可以导入一个类型或一个值, 但是使用import type导入的值, 只能在类型上下文中使用, 不能作为一个值来使用, 而import导入的类型和值, 都可以按照其原本定义来使用。- 后续会持续更新,在构建项目和开发遇到的问题