最近項(xiàng)目用了nuxt,又想用typescript,于是摸索了很久有了這篇文章
說明:最新版的腳手架已經(jīng)支持創(chuàng)建TypeScript項(xiàng)目了,直接命令行創(chuàng)建接口
nuxt官方有typescript的教程:https://typescript.nuxtjs.org/。
我們需要安裝三個依賴包:
-
@nuxt/types
包含 Nuxt 的 TypeScript 的一些類型定義。
這個包已經(jīng)在 @nuxt/typescript-build 以及 @nuxt/typescript-runtime 引入了,如果已引入上面兩個包,無需再顯式的引入了。 -
@nuxt/typescript-build
能讓 Nuxt 在 layouts, components, plugins 和 middlewares 中使用 TypeScript。 -
@nuxt/typescript-runtime
暫時不需要,先不做介紹
警告
這些包只支持 Nuxt 2.10 or 更高版本.
安裝
官方推薦yarn安裝,實(shí)際上我在windows上用npm安裝是有問題的
yarn add --dev @nuxt/typescript-build
然后在nuxt.config.js中的 buildModules 中加入 @nuxt/typescript-build
// nuxt.config.js
export default {
buildModules: ['@nuxt/typescript-build']
}
然后在根目錄創(chuàng)建一個tsconfig.json的文件,這個是typescript的配置,內(nèi)容可以如下:
// tsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"moduleResolution": "node",
"experimentalDecorators": true,
"lib": [
"esnext",
"esnext.asynciterable",
"dom",
"dom.iterable" //這里是新增項(xiàng)
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"~/*": [
"./*"
],
"@/*": [
"./*"
]
},
"types": [
"@types/node",
"@nuxt/types"
]
},
"exclude": [
"node_modules"
]
}
為了使用typescript的最新語法,我們將
target字段設(shè)置成了es2020,
為了使用裝飾器將experimentalDecorators設(shè)置成了true
為了能讓typscript識別vue文件你也需要在根目錄加入vue-shim.d.ts文件
declare module "*.vue" {
import Vue from 'vue'
export default Vue
}
然后將package.json里面的scripts命令改一下
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "cross-env NODE_ENV=production node server/index.js",
"generate": "nuxt generate",
"lint": "eslint --ext .ts,.vue ."
},
最后將我們的文件除了(server/index.js和nuxt.config.js)都改成.ts類型
執(zhí)行命令
yarn dev
就可以在本地啟動啦!