在NextJs中使用绝对路径导入无法正常工作

时间:2020-10-16 22:36:05

标签: node.js next.js

我在路由中创建了一个名为jsconfig.json的文件:

{
  "compilerOptions": {
    "baseUrl": "."
  }
}

我有最新的nextjs "next": "latest"

当前要导入组件,我必须执行以下操作:

import AppHeader from "../../../../components/common/AppHeader";

但是,经过以上这些更改,我认为我可以做到:

import AppHeader from "src/components/common/AppHeader";

但我收到此消息:

未找到模块:无法解析'src / components / common / AppHeader'

目录结构:

/
-->lib
-->src
   -->components
-->public

有什么想法吗? 我也尝试将其添加到我的next.config.js文件中,但没有任何区别: config.resolve.modules.push(__dirname)

2 个答案:

答案 0 :(得分:0)

尝试使用我的 tsconfig.json,它对我有用:

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "resolveJsonModule": true
  }
}

如果你在生产模式下运行它也可能是运行脚本的原因 就我而言,我使用:

"build": "nest build"
"start:prod": "node dist/src/main"

答案 1 :(得分:0)

删除 src 文件夹并将组件直接放在源文件夹中,然后在 jsconfig.json 中执行以下操作:

{
"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "src/components/*": ["components/*"],
      "src/lib/*": ["lib/*"]
    }
  },
  "exclude": [
    "node_modules"
  ]
}

现在您可以像这样访问您的文件夹:

src/components/..
src/lib/..
相关问题