Mike Hawkins
Mike Hawkins

Reputation: 2304

Vue component cannot resolve relative component imports in typescript

I just upgraded to typescript using the vue-cli vue upgrade typescript command. The command exits succesfully.

However, now, the relative imports that previously worked in javascript can no longer be resolved.

I have the following Home component, that imports another component:

<script lang="ts">
    import Navbar from "./Navbar"

    export default {
        name: "Home",
        components: {
            Navbar
        }
    }
</script>

The Navbar component:

<script lang="ts">
export default {
    name: "Navbar"
}
</script>

The import Navbar from "./Navbar" statement in the home component gives me the following error: Cannot find module './Navbar'.Vetur(2307)

I suspect it has something to do with the tsconfig configuration. It's auto generated as part of the automatic typescript upgrade:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}

Upvotes: 0

Views: 2551

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50777

This is correct. The reason this occurs is that the vetur cannot find the path to the module ./Navbar. However, it can find the path to ./Navbar.vue.

You can see from the comment by a Vetur maintainer that importing components without the .vueextension is not supported.

You will also need to declare a vue-shim.d.ts that declares the typings for .vue so you don't get explosions there, as well:

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

Now, mind you, this will only happen in files where the script lang="ts", outside of that you won't see this issue as Vetur will not process any of the javascript within the script block as typescript (true for SFCs)

Upvotes: 3

Related Questions