相关文章推荐
坚韧的哑铃  ·  springboot+websocket+s ...·  1 年前    · 
直爽的黄花菜  ·  [Day23] ...·  3 年前    · 
耍酷的跑步机  ·  Antd3.0 基于 DatePicker ...·  3 年前    · 
  • More

  • Nuxt 的 TypeScript 支持主要是通过 @nuxt/typescript-build 这个 Nuxt 模块提供。

    此章节提供了此模块 安装 以及 设置 的方法。

    yarn add --dev @nuxt/typescript-build @nuxt/types
    
    npm install --save-dev @nuxt/typescript-build @nuxt/types
    

    你只需在 nuxt.config.ts 中的 buildModules 中加入 @nuxt/typescript-build

    nuxt.config.ts
    import type { NuxtConfig } from '@nuxt/types'
    const config: NuxtConfig = {
      buildModules: ['@nuxt/typescript-build']
    export default config
    

    然后再创建 tsconfig.json 文件 :

    tsconfig.json
    {
      "compilerOptions": {
        "target": "ES2018",
        "module": "ESNext",
        "moduleResolution": "Node",
        "lib": [
          "ESNext",
          "ESNext.AsyncIterable",
          "DOM"
        "esModuleInterop": true,
        "allowJs": true,
        "sourceMap": true,
        "strict": true,
        "noEmit": true,
        "baseUrl": ".",
        "paths": {
          "~/*": [
            "./*"
          "@/*": [
            "./*"
        "types": [
          "@nuxt/types",
          "@nuxt/typescript-build",
          "@types/node"
      "exclude": [
        "node_modules"
    

    请注意,若你要使用 Optional ChainingNullish Coalescing 语法,请将 tsconfig 中的 target 设置成 ES2018。如果你设置成 ESNext 的话,则不会如期运作,因为目前看起来 ESNext 尚未支持这些特性。

    你也需要加入下方的类型声明文件来为 Vue 提供类型

    vue-shim.d.ts
    declare module "*.vue" {
      import Vue from 'vue'
      export default Vue
    

    查看 TypeScript 文档 来了解编译器的更多选项。

    如果你是通过编程式的方式来创建一个自定义服务器框架时,请注意: 你需要确保 Nuxt 在构建 (Building) 之前已经准备好 (Ready):

    // 确保再继续之前等待 Nuxt 加载 @nuxt/typescript-build
    await nuxt.ready()
    if (config.dev) {
      const builder = new Builder(nuxt)
      await builder.build()
    

    至此,你已经可以在 layouts, components, pluginsmiddlewares 中使用 TypeScript 了!

    你也可以在 更多使用方式 中了解 Nuxt 项目使用 TypeScript 的其他方式。

    typeCheck

    在单独的进程中启用 TypeScript 的类型检查。

  • 类型: Boolean or Object
  • 缺省: true
  • 当打开时, Nuxt 会使用 fork-ts-checker-webpack-plugin 来启用类型检查。

    你也可以通过传入 Object 来覆盖选项,或是设置成 false 以禁用。

    ignoreNotFoundWarnings

    隐藏 “未找到 TypeScript” 警告。

  • 类型: Boolean
  • 缺省: false
  • 当选项启用后,可以隐藏 export ... was not found ... 的警告。

    在这个链接中可以了解更多信息

    警告: 这个选项启用时,可能会把你想看到的一些警告一并隐藏,在打开之前请三思。

    loaders

    自定义 ts-loader 选项

  • 类型: Object
  • 如果你需要额外添加 TypeScript 加载器选项,可以通过 loaders.tsloaders.tsx 分别对 tstsx 这两种不同的文件类型进行自定义。

    nuxt.config.ts
    import type { NuxtConfig } from '@nuxt/types'
    const config: NuxtConfig = {
      typescript: {
        loaders: {
          ts: {
            silent: true
          tsx: {
            silent: true