vue3&vite
放弃webpack,使用vite安装vue3.0
这个是尤大开发的新工具,目的是以后替代webpack,原理是利用浏览器现在已经支持es6的import了,遇到import会发送一个http请求去加载文件,vite拦截这些请求,做一些预编译,省去了webpack冗长打包的时间,提升开发体验npm install -g create-vite-app
create-vite-app
cd vue3-vite
npm install
npm run dev
# 或者使用yarn
yarn add -g create-vite-app
yarn create vite-app
yarn
yarn dev
引入typescript# 安装 typescript
yarn add typescript -D
初始化tsconfig.jsonnpx tsc --init
将main.js修改为main.ts,同时将index.html里面的引用也修改为main.ts,
然后在script 里添加 lang="ts"
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: { HelloWorld }
}
修改完之后,重启就可以访问项目了。虽然这样配置是可以了,但是打开main.ts会发现import App from App.vue会报错,这是因为现在ts还没有识别vue文件,需要进行下面的配置:
在项目根目录添加shim.d.ts文件,添加以下内容declare module "*.vue" {
import type { DefineComponent } from "vue";
const component: DefineComponent;
export default component;
}
安装vue-routeryarn add vue-router@4.0
这样可以选择最新的vue-router 4.0.0的测试版本,这里更新到beta.13
配置vue-router
在项目src目录下面新建router目录,然后添加index.ts文件,在文件中添加以下内容import { createRouter, createWebHashHistory } from "vue-router";
// 在 Vue-router新版本中,需要使用createRouter来创建路由
export default createRouter({
// 指定路由的模式,此处使用的是hash模式
history: createWebHashHistory(),
// 路由地址
routes: [],
});
安装vuex
同上yarn add vuex@4.0
目前只能选择最新测试版
在项目src目录下面新建store目录,并添加index.ts文件,文件中添加以下内容import { createStore } from "vuex";
interface State {
userName: string;
}
export default createStore({
state: { userName: "xiuluo" },
});
main.ts中引入vuex和vue-routerimport { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router/index'
import vuex from './store/index'
const app = createApp(App)
app.use(router)
app.use(vuex)
app.mount('#app')
vuex
使用vuex
效果