Nuxt + Typescript最佳實(shí)踐1:支持TypeScript

最近項(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.jsnuxt.config.js)都改成.ts類型

執(zhí)行命令

yarn dev

就可以在本地啟動啦!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容