【问题标题】:Module not found: Can't resolve module in Next.js | Module not found: Can't resolve 'path'未找到模块:无法解析 Next.js 中的模块 |找不到模块:无法解析“路径”
【发布时间】:2021-10-16 04:01:16
【问题描述】:

这个问题之前在 StackOverFlow 中也有人问过,但是没有找到一个正确的答案可以完全解决这个问题。

我在一个 next.js 入门应用程序中遇到了这个问题(我还在学习中)。

posts.js 库文件

import fs from "fs";
import path from "path";
import matter from "gray-matter";

const postsDirectory = path.join(process.cwd(), "posts");

//The 
export function getSortedPostsData() {

//The rest of the codes...

}

错误

./lib/posts.js:2:0
Module not found: Can't resolve 'path'
  1 | import fs from "fs";
> 2 | import path from "path";
  3 | import matter from "gray-matter";
  4 | 
  5 | const postsDirectory = path.join(process.cwd(), "posts");

next.config.js

module.exports = {
  reactStrictMode: true,
  webpack5: true,
  webpack: config => {
    config.resolve.fallback = { fs: false };

    return config;
  }
};

最初错误发生在这个->

import fs from "fs"

但是在 next.config.js 中添加 webpack 配置行之后 错误转移到下一行 ->

import path from "path"

注意:我在 index.js 文件中实现了 getStaticProps,它调用了上述库

index.js 文件

export async function getStaticProps() {
  const allPostsData = getSortedPostsData();

  return {
    props: {
      allPostsdata
    }
  };
}

【问题讨论】:

  • 您是否在代码中的其他任何地方使用getSortedPostsData?例如在 React 组件内部?
  • @juliomalves 是的。它在我的 Home 组件页面中的 getStaticProps() 内部调用,该函数的结果作为 getStaticProps 的 prop 返回并传递给 Home 组件。

标签: javascript node.js reactjs next.js


【解决方案1】:

我认为你不能这样做path.join(process.cwd(),这没有任何意义,如果你这样做,你的路径将与你调用该脚本的当前工作目录连接。请改用path.join(__dirname, 'file')

【讨论】:

    猜你喜欢
    • 2021-02-06
    • 2022-06-13
    • 2021-07-17
    • 2018-04-17
    • 2018-10-01
    • 2018-10-28
    • 2017-10-23
    • 2018-01-20
    • 1970-01-01
    相关资源
    最近更新 更多