在NextJs中使用绝对路径导入不起作用

7

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

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

我有最新的Next.js "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)

我能了解一下你的文件夹结构吗?我猜你可以尝试将 src/components/common/AppHeader 替换为 components/common/AppHeader - nghiaht
我已经更新了我的问题。我尝试了你提到的方法,但是它显示模块未安装。我还想使用绝对路径访问lib中的内容。 - strangeQuirks
1
我最终选择了使用webpack的这个解决方案:https://dev59.com/mFIH5IYBdhLWcg3weucq#59542342 config.resolve.modules.push(path.resolve('./')) - strangeQuirks
这个回答解决了你的问题吗?在NextJS中使用jsconfig.json中的baseUrl无效 - juliomalves
6个回答

6

看起来你的文件夹结构如下:

根目录->src->components

在你的jsconfig文件中添加另一个属性。

{

   "compilerOptions": {
     "baseUrl": "."
    },
 
    "include":["."]

}

3

对于那些需要帮助的人,这个方法适用于我。将以下内容添加到你的tsconfig.json文件中。

tsconfig.json

  "module": "CommonJS",
  "baseUrl": ".",
  "paths": {
    "@/layouts/*": ["src/layoyts/*"],
    "@/components/*": ["src/components/*"],
    "@/public/*": ["./public/*"]
  }

tsconfig.json或jsconfig.json。这个答案中的路径部分帮助我解决了我的问题。我使用“@”来声明每个在某个导入中使用的根路径,以实现绝对路径。 - Florian G

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
在 jsconfig.json 中执行以下操作:
{
"compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "src/*": ["src/*"]
    }
  },
  "exclude": [
    "node_modules"
  ]
}

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

src/components/..
src/lib/..

-2

使用npm install --save-dev typescript @types/react命令安装@types。

您的tsconfig.json文件应该类似于以下内容:

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "paths": {
      "@/components/*": [
        "components/*"
      ],
      "@/public/*": [
        "public/*"
      ]
    },
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "incremental": true,
    "esModuleInterop": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": [
    "."
  ],
  "exclude": [
    "node_modules"
  ]
}

-2

你的配置对我很有用。只需停止并重新启动nextJs服务器即可。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接