Search code examples
typescriptvue.jsnuxt.jstsconfig

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


I have setup Nuxt with TypeScript using the instructions from https://typescript.nuxt.org. The transition was pretty seamless and ok, except that I can't get rid of this error that nuxt:typescript "Cannot find module", which obviously is a false-positive.

My imports look like this:

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

I have tried with ~/ and without the .vue extension. Nothing works.

My tsconfig.json looks like this:

{
  "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"]
}

And I have this object in my nuxt.config.js:

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

Error example


Solution

  • I found the solution here: https://github.com/nuxt/typescript/issues/153#issuecomment-543010838

    Basically, create a ts-shim.d.ts in your root directory with these contents:

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

    As for your tsconfig.json, make sure you have these entries in there:

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

    This solved my problems with both .vue imports and .ts imports.

    Note! It is now absolutely mandatory to include .vue at the end of your Vue imports, otherwise the imports will fail:

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