【问题标题】:Why can't Next.js import files under a folderNext.js为什么不能导入文件夹下的文件
【发布时间】:2021-04-12 01:06:15
【问题描述】:
Module not found: Can't resolve 'components/layout's Codes\nextjs-blog\pages\posts'
> 1 | import Layout from 'components/layout'
  2 | import Link from 'next/link'
  3 | import Head from 'next/head'

好的,这是错误消息,我得到了任何人的想法

我的组件文件夹在 nextjs-blog 下,给出错误的 js 文件在帖子下

我没有提供太多信息,因为我是 Next js 新手,不知道任何人需要什么

如果我这样做它不起作用

import Layout from '../components/layout'

Desktop/Marti's Codes/nextjs-blog

我在基本文件夹中添加了组件文件夹,在组件中我有两个文件: 布局.js layout.module.js

然后在页面中我有帖子文件夹和 first-post.js 这是从组件中导入布局文件的文件

【问题讨论】:

  • import Layout from '../../components/layout' 怎么样?这似乎是您所描述的正确相对路径。
  • 我很确定我尝试了“../../components/layout”,但它似乎可以工作,谢谢

标签: javascript reactjs next.js


【解决方案1】:

应该是

import Layout from '../../components/layout'

感谢juliomalves的回答

【讨论】:

    【解决方案2】:

    您需要使用相对路径来导入组件,即../components/layout

    要使用像components/layout 这样的绝对导入,我们在jsconfig.json 中设置如下别名。

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "@/components/*": ["components/*"]
        }
      }
    }
    

    并像这样使用

    import Layout from '@/components/layout' 
    

    参考:https://nextjs.org/docs/advanced-features/module-path-aliases

    【讨论】:

    • 好吧,我一开始使用的例子显示我是这样使用它的,但没有区别
    • 能分享一下组件的文件夹位置和你的pages文件夹吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 2020-06-09
    • 2016-05-11
    • 2011-07-25
    相关资源
    最近更新 更多