參考鏈接:https://blog.csdn.net/weixin_44897255/article/details/109119336
一直被vue項(xiàng)目的啟動(dòng)等待绎晃,和webpack打包卡慢所困擾榕暇,現(xiàn)在有了新技術(shù),就趕緊來(lái)體驗(yàn)一波哩都。新技術(shù)如下:
yarn + vite + vue 3 + ts + vue-router 4
yarn是比npm好用的包管理工具板乙,更快谓松,更簡(jiǎn)潔焕妙,更好看,自從用上yarn之后愚争,就沒(méi)再敲過(guò)npm映皆。
vite是一種全新的前端構(gòu)建工具挤聘,是揚(yáng)言要替代webpack的存在轰枝,特點(diǎn)是快,快得離譜组去。
vue 3是vue的最新版本鞍陨,相比較vue 2,特點(diǎn)是更小从隆,更快诚撵,反正就是比你聰明比你強(qiáng)。
ts是js的類(lèi)型控制系統(tǒng)键闺,比js更嚴(yán)謹(jǐn)更規(guī)范寿烟,類(lèi)似于stylus、sass這樣的css預(yù)處理器辛燥,ts是js的預(yù)處理器筛武。
vue-router 4是vue的路由系統(tǒng),單頁(yè)面應(yīng)用的好伴侶挎塌,這是適配了vue 3的新版本徘六。
1.創(chuàng)建項(xiàng)目
yarn create vite-app demo
cd demo
yarn
yarn dev
創(chuàng)建項(xiàng)目的時(shí)候vite沒(méi)有像vue-cli那樣,有那么多問(wèn)題問(wèn)你榴都,要不要使用css預(yù)處理器啊待锈,要不要使用history模式啊。
vite人狠話不多嘴高,直接給你安裝個(gè)最基本的只包含了vue3.0的項(xiàng)目竿音,后面的你自己玩吧。
這里我認(rèn)為是新東西還不完善拴驮,各方面適配兼容配置還有點(diǎn)問(wèn)題春瞬,還沒(méi)法像vue-cli4那樣,一口氣搞定莹汤。
2.配置ts
yarn add typescript -D
npx tsc --init
將main.js改完main.ts快鱼,記得把index.html的引入也改為main.ts。
然后在根目錄添加shim.d.ts文件,內(nèi)容如下:
declare module "*.vue" {
import { Component } from "vue";
const component: Component;
export default component;
}
3.配置vue-router
yarn add vue-router@next
在src目錄新建router文件夾抹竹,在router文件夾里新建index.ts线罕,內(nèi)容如下:
// router/index.ts
import { createRouter, createWebHashHistory } from "vue-router";
import Home from "../views/home.vue";
const routes = [
{ path: "/", name: "Home", component: Home },
{
path: "/about",
name: "About",
component: () => import("../views/About.vue"),
},
];
// Vue-router新版本中,需要使用createRouter來(lái)創(chuàng)建路由
export default createRouter({
// 指定路由的模式,此處使用的是hash模式
history: createWebHashHistory(),
routes, // short for `routes: routes`
});
然后在main.ts中引入
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router/index'
const app = createApp(App)
app.use(router)
app.mount('#app')
為了更好地切換路由查看效果窃判,我在src目錄新建了views目錄钞楼,新建了home.vue和about.vue。
home.vue
<template>
<div class="home">
<h1>This is an home page</h1>
</div>
</template>
同時(shí)在app.vue中做了相應(yīng)的修改:
<template>
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Hello Vue 3.0 + Vite" />
<router-link to="/">home</router-link>
<router-link to="/about">about</router-link>
<router-view></router-view>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
a{
margin: 10px;
}
</style>
啟動(dòng)看看
yarn dev
這樣一頓操作下來(lái)袄琳,類(lèi)似于原來(lái)vue-cli4搭建的項(xiàng)目的vue3新項(xiàng)目就搭建好了询件。
后面可以再加上axios和element-ui之類(lèi)的,這里就不再多啰嗦了唆樊。
起飛