为什么在Next.js 12中导入别名不工作?

vdzxcuhz  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(116)

以下是我的选择:

{
  "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”或其相应的类型声明。
x1c 0d1x的数据
当我在next.config.js中添加webpack配置时:

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


它编译,但仍然显示错误的vs代码。

4urapxun

4urapxun1#

我尝试了一些调整你的配置,它为我工作。首先设置baseUrl路径到src目录,然后重新启动您的TS服务器:Ctrl + Shift + PF1 >TypeScript:重新启动TS服务器

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

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

import Header from "@/containers/dashboard";


如果你的项目中有JavaScript文件,并且你想导入它们,我建议设置"allowJs": true

相关问题