为什么 next js 12 中的导入别名不起作用?

问题描述 投票:0回答:1

这是我的编译选项:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": false,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    // "jsxImportSource": "@emotion/react",
    "incremental": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"],
      "@/assets/*": ["assets/*"],
      "@/config/*": ["config/*"],
      "@/pages": ["pages/"],
      "@/public/*": ["public/*"],
      "@src/": ["src/"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    "src/**/*.ts",
    "src/**/*.tsx",
  ],
  "references": [
    {
      "path": "./tsconfig.node.json"
    }
  ],
  "exclude": ["node_modules"]
}

在我的项目结构中,我在根目录中列出了所有列出的路径。 我仍然收到此错误:

找不到模块“@/src/containers/dashboard”或其相应的类型声明。

当我在 next.config.js 中添加 webpack 配置时:

webpack(config) {
config.resolve.alias = {
  ...config.resolve.alias,
  '@': path.resolve(__dirname),
  '@/src/*': path.resolve(__dirname, 'src/*'),
};

它可以编译,但在 vs code 中仍然显示错误。

typescript next.js import refactoring
1个回答
0
投票

我尝试了你的配置并进行了一些调整,它对我有用。首先将

baseUrl
路径设置为
src
目录,然后重新启动 TS Server:
Ctrl + Shift + P
F1
> TypeScript:重新启动 TS Server

{
  "compilerOptions": {
    "baseUrl": "src/",
    "paths": {
      "@/*": ["*"],
      "@/assets/*": ["assets/*"],
      "@/config/*": ["config/*"],
      "@/pages": ["pages/"],
      "@/public/*": ["public/*"],
      "@src/": ["src/"]
    },
  },
}

现在您应该能够根据需要导入组件:

import Header from "@/containers/dashboard";

如果您的项目中有 JavaScript 文件并且想要导入它们,我建议设置

"allowJs": true

© www.soinside.com 2019 - 2024. All rights reserved.