以下是我的目录结构
-shared
--foo.ts
-web-ui (nuxt project)
--pages
--index.vue
--index.ts
--tsconfig.json
我的nuxt tsconfig如下所示。
{
// https://v3.nuxtjs.org/concepts/typescript
"extends": "./.nuxt/tsconfig.json",
"compilerOptions": {
"paths": {
"~shared/*": ["../shared/*"]
},
"rootDirs": [".", "../shared"]
}
}
我的新index.vue
如下
<template>
<div>
<h1>Welcome to the homepage {{ foo }}</h1>
</div>
</template>
<script src="./index.ts" setup lang="ts" />
我的index.ts
如下。
import { useFoo } from '~shared/foo'
const foo = useFoo;
我得到了以下错误。
[plugin:vite:import-analysis] Failed to resolve import "~shared/foo" from "pagesindex.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.
我在这里做错了什么?
Nuxt建议不要覆盖项目根目录中tsconfig.json中的路径
此处的文档:https://nuxt.com/docs/guide/directory-structure/tsconfig
请注意,如果您需要自定义路径,这将覆盖自动生成的路径别名。相反,我们建议您添加nuxt.config 中alias属性所需的路径别名
您需要将其添加到nuxt.config.ts
alias: {
"~shared": fileURLToPath(new URL("./shared", import.meta.url)),
},
重新运行nuxt服务器,现在在您的index.ts中,您现在可以导入useFoo
import import { useFoo } from '~shared/foo'