如何用Vue+TypeScript項目配置實戰?本文教你
❝最近想學習一下TypeScript語法,但是隻是看官方文檔又有些乏味,還是通過項目在實踐中學習比較有趣,所以在這裏記錄一下我的學習歷程,與Vue項目結合開發。
❞
項目搭建
通過腳手架搭建
1. 通過Vue CLI 3 創建vue項目
vue create vue-typescript
// 在此選擇typescript支持
? Check the features needed for your project: () Babel () TypeScript ( ) Progressive Web App (PWA) Support () Router () Vuex >() CSS Pre-processors () Linter / Formatter ( ) Unit Testing ( ) E2E Testing 我是08年出道的高級前端架構師,有問題或者交流經驗可以進我的扣扣裙 519293536 我都會盡力幫大家哦
複製代碼
// 引入 vue-class-component 插件 // 以下大概是我的選擇 ? Use class-style component syntax? (Y/n) y ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass) ? Pick a linter / formatter config: Prettier ? Pick additional lint features: Lint on save ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files ? Save this as a preset for future projects? (y/N) n
複製代碼
2. 啓動項目
yarn run serve
能跑起來嗎,能跑就是好項目😂
3.項目配置
此時其實腳手架已經幫我們配置好了大多數的配置,但還是需要熟悉一下配置。
tsconfig.json
在項目根目錄下創建tsconfig.json
。
{
// 編譯選項
"compilerOptions": {
// 輸出目錄
"outDir": "./output",
// 是否包含可以用於 debug 的 sourceMap
"sourceMap": true,
// 以嚴格模式解析
"strict": true,
// 採用的模塊系統
"module": "esnext",
// 如何處理模塊
"moduleResolution": "node",
// 編譯輸出目標 ES 版本
"target": "es5",
// 允許從沒有設置默認導出的模塊中默認導入
"allowSyntheticDefaultImports": true,
// 將每個文件作爲單獨的模塊
"isolatedModules": false,
// 啓用裝飾器
"experimentalDecorators": true,
// 啓用設計類型元數據(用於反射)
"emitDecoratorMetadata": true,
// 在表達式和聲明上有隱含的any類型時報錯
"noImplicitAny": false,
// 不是函數的所有返回路徑都有返回值時報錯。
"noImplicitReturns": true,
// 從 tslib 導入外部幫助庫: 比如__extends,__rest等
"importHelpers": true,
// 編譯過程中打印文件名
"listFiles": true,
// 移除註釋
"removeComments": true,
"suppressImplicitAnyIndexErrors": true,
// 允許編譯javascript文件
"allowJs": true,
// 解析非相對模塊名的基準目錄
"baseUrl": "./",
// 指定特殊模塊的路徑
"paths": {
"jquery": [
"node_modules/jquery/dist/jquery"
]
},
// 編譯過程中需要引入的庫文件的列表
"lib": [
"dom",
"es2015",
"es2015.promise"
]
}
}
tslint.json
在根路徑下創建tslint.json
文件,就是 引入 ts
的 standard
規範。
如果已經引入了eslint的配置文件,這一步其實也可以不做。
{
"extends": "tslint-config-standard",
"globals": {
"require": true
}
}
附上一個腳手架自動生成的eslint的默認配置 eslintrc.js
。
module.exports = {
root: true,
env: {
node: true
},
extends: [
"plugin:vue/essential",
"eslint:recommended",
"@vue/typescript/recommended",
"@vue/prettier",
"@vue/prettier/@typescript-eslint"
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
"no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"
}
};
4.支持ES6 / ES7
在 tsconfig.json
中,添加對es6 / es7
的支持,更多的配置請見tsconfig - 編譯選項。
"lib": [
"dom",
"es5",
"es6",
"es7",
"es2015.promise"
]
5.配置Vuex
首先當然是先安裝依賴啦。
yarn add vuex vuex-class
- vuex:在
vue
中集中管理應用狀態 - vuex-class :在
vue-class-component
寫法中 綁定vuex
。
引用了vuex-class
之後還是和原來的寫法有點兒區別的。
vuex store 中該怎麼寫,還怎麼寫,引用的時候如下:
import { Component, Prop, Vue } from "vue-property-decorator";
import { State, Getter, Action, Mutation, namespace } from "vuex-class";
// 聲明使用的是哪個模塊
const commonModule = namespace("common");
@Component
export default class HelloWorld extends Vue {
@Prop() private msg!: string;
// 獲取vuex中的數據
@commonModule.State("token") token!: string;
@commonModule.Getter("getToken") getToken!: string;
@commonModule.Action("setToken") actionSetToken: (arg0: string) => void;
@commonModule.Mutation("setToken") mutationSetToken: unknown;
// @State token
// @Getter("token") getterToken;
// @Action("token") actionToken;
// @Mutation("token") mutationToken;
created() {
this.actionSetToken("123");
alert(this.token);
}
}
6.支持 vue mixin 函數
在src下新建mixins目錄,根據業務複用模塊劃分結構。
在使用Vue
進行開發時我們經常要用到混合,結合TypeScript
之後一般有兩種mixins
的方法。
一種是vue-property-decorator
提供的
// 定義 routerMixins.ts文件
// mixin router 公共方法
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
export default class myMixins extends Vue {
/**
* @author: WangXinYu
* @describe: 瀏覽器後退事件
* @param: {}
* @return:
**/
goBack() {
this.$router.go(-1)
}
/**
* @author: WangXinYu
* @describe: test
* @param: {}
* @return:
**/
routerTest() {
console.log('are you ok?')
}
}
// 引入 mixin
import { Component, Prop, Vue, Mixins } from 'vue-property-decorator'
import routerMixins from '@/mixins/router'
@Component
export default class HelloWorld extends Mixins(routerMixins) {
created() {
this.routerTest()
}
}
第二種是在@Component
中混入。
// mixins.ts
import { Vue, Component } from 'vue-property-decorator';
declare module 'vue/types/vue' {
interface Vue {
value: string;
}
}
@Component
export default class myMixins extends Vue {
value: string = 'Hello'
}
// 混入
import { Vue, Component, Prop } from 'vue-property-decorator';
import myMixins from '@/mixins/myMixins';
@Component({
mixins: [myMixins]
})
export default class myComponent extends Vue{
created(){
console.log(this.value) // => Hello
}
}