上周墅诡,發(fā)現(xiàn)vue版本更新到了2.5壳嚎,這次主要update了對typescript(以下簡稱ts)的支持,正好末早,對我廠現(xiàn)有項(xiàng)目中加入ts使用烟馅,也是一直在醞釀當(dāng)中的事情,所以寫下這篇博客記錄下其中踩的坑然磷。
首先一定是安裝相對應(yīng)的依賴模塊 npm install typescript ts-loader --save-dev
確認(rèn)安裝完成之后在webpack中加入對ts的loader配置
{
test:/\.ts$/,
exclude:/node_modules|vue\/src/,
loader:'ts-loader',
options: {
appendTsSuffixTo: [/\.vue$/]
}
}
為了識別.vue文件中ts代碼郑趁,在src目錄下新建vue-shims.d.ts,編輯這個文件
declaremodule"*.vue"{
importVuefrom"vue";
exportdefaultVue;
}
在項(xiàng)目根目錄下新建tsconfig.json文件姿搜,注意加粗的的字段一定別忘記添加寡润,這是后面對vue-class-component這個插件的支持
{
"compilerOptions": {
"allowSyntheticDefaultImports":true,
**"experimentalDecorators":true,**
"lib": [
"dom",
"es5",
"es2015.promise"
],
"module":"es2015",
"moduleResolution":"node",
"isolatedModules":false,
"target":"es5"
},
"include": [
"./src/**/*.ts"
]
}
然后js入口文件命名需要改成.ts 如 './src/main.ts'
這時(shí)候我們需要引入vue-class-component這個插件對vue中class風(fēng)格代碼進(jìn)行支持
npm install --save-dev vue-class-component
安裝完成后我們就可以愉快的使用ts進(jìn)行開發(fā)啦
這里給出相關(guān)的示例代碼參考,寫法與es6寫法略有不同痪欲,需要注意的sciprt標(biāo)簽上lang需要寫成ts悦穿,官方也給出了sample進(jìn)行參考 https://github.com/vuejs/vue-class-component#vue-class-component
App.vue
hello.vue
目前,遺留下來的一個問題业踢,當(dāng)我在嘗試引入vue-resource時(shí)會報(bào)錯栗柒,暫時(shí)找不到解決方案,有知道的同學(xué)告訴一聲哈
更新一下這個解決方案 https://segmentfault.com/q/1010000011662554?_ea=2716766