Search code examples
typescriptvue.jsvitetsconfignuxt3.js

Nuxt 3 tsconfig path is not working from parent directory


Following is my directory structure

-shared
    --foo.ts
-web-ui (nuxt project)
    --pages
        --index.vue
        --index.ts
    --tsconfig.json

My nuxt tsconfig is as below.

{
  // https://v3.nuxtjs.org/concepts/typescript
  "extends": "./.nuxt/tsconfig.json",
  "compilerOptions": {
    "paths": {
      "~shared/*": ["../shared/*"]
    },
    "rootDirs": [".", "../shared"]
  }
}

My nuxt index.vue is as below

<template>
  <div>
    <h1>Welcome to the homepage {{ foo }}</h1>
  </div>
</template>

<script src="./index.ts" setup lang="ts" />

My index.ts is as below.

import { useFoo } from '~shared/foo'

const foo = useFoo;

I am getting below error.

[plugin:vite:import-analysis] Failed to resolve import "~shared/foo" from "pages\index.ts?macro=true". Does the file exist?
C:/Projects/GitLab/legal-disco-typescript/web-ui/pages/index.ts:1:0
1  |  import { useFoo } from "~shared/foo";
   |                          ^
2  |  const foo = useFoo;
3  |
    at formatError (file:///C:/Projects/GitLab/my-project-typescript/web-ui/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:40862:46)
    at TransformContext.error (file:///C:/Projects/GitLab/my-project-typescript/web-ui/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:40858:19)
    at normalizeUrl (file:///C:/Projects/GitLab/my-project-typescript/web-ui/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:37595:33)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async TransformContext.transform (file:///C:/Projects/GitLab/my-project-typescript/web-ui/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:37728:47)
    at async Object.transform (file:///C:/Projects/GitLab/my-project-typescript/web-ui/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:41111:30)
    at async loadAndTransform (file:///C:/Projects/GitLab/my-project-typescript/web-ui/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:37373:29
Click outside or fix the code to dismiss.
You can also disable this overlay by setting server.hmr.overlay to false in vite.config.js.

What am I doing wrong here?


Solution

  • Nuxt advises against overriding the path in tsconfig.json in the root of the project

    documentation here: https://nuxt.com/docs/guide/directory-structure/tsconfig

    note that if you need to customize your paths, this will override the auto-generated path aliases. Instead, we recommend that you add any path aliases you need to the alias property within your nuxt.config

    You need to add it to nuxt.config.ts

      alias: {
        "~shared": fileURLToPath(new URL("./shared", import.meta.url)),
      },
    

    re-run nuxt server and now in your index.ts you can now import useFoo

    import import { useFoo } from '~shared/foo'