Nuxt TypeScript error: nuxt:typescript Cannot find module '@/my-module'

Nuxt TypeScript error: nuxt:typescript Cannot find module '@/my-module'

我已经按照 https://typescript.nuxt.org 中的说明使用 TypeScript 设置了 Nuxt。过渡非常无缝而且还可以,除了我无法摆脱这个 nuxt:typescript "Cannot find module" 的错误,这显然是一个误报。

我的导入是这样的:

import InputField from '@/components/InputField.vue'

我试过 ~/ 而没有 .vue 扩展名。没有任何效果。

我的 tsconfig.json 看起来像这样:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": ["esnext", "esnext.asynciterable", "dom"],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": ".",
    "paths": {
      "~/*": ["src/*"],
      "~*": ["src/*"],
      "@/*": ["src/*"]
    },
    "types": ["@types/node", "@nuxt/types"]
  },
  "exclude": ["node_modules"]
}

我的 nuxt.config.js 中有这个对象:

typescript: {
  typeCheck: {
    eslint: true,
    vue: true
  }
}

我在这里找到了解决方案:https://github.com/nuxt/typescript/issues/153#issuecomment-543010838

基本上,在您的根目录中创建一个 ts-shim.d.ts,内容如下:

declare module '*.vue' {
  import Vue from 'vue';
  export default Vue
}

至于你的 tsconfig.json,确保你有这些条目:

{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "~/*": ["./*"],
      "@/*": ["./*"]
    }
  }
}

这解决了我的 .vue 导入和 .ts 导入问题。

注意! 现在绝对必须在 Vue 导入的末尾包含 .vue,否则导入将失败:

import SomeComponent from '~/components/SomeComponent.vue'