Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 757
aborted Avatar asked Oct 20 '19 16:10

aborted


People also ask

Does Nuxt support TypeScript?

Besides these packages, Nuxt also provides an optional TypeScript runtime support using the @nuxt/typescript-runtime module. According to the documentation, TypeScript runtime support is needed for files such as the nuxt.

What is a module in Nuxt?

Modules are Nuxt extensions which can extend the framework's core functionality and add endless integrations. Once you have installed the modules you can then add them to your nuxt. config. js file under the modules property.

Is Nuxt a library or framework?

Nuxt is an open-source framework under MIT license for building modern and performant web applications that can be deployed on any platform running JavaScript.


1 Answers

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'
like image 74
aborted Avatar answered Oct 20 '22 14:10

aborted