【发布时间】: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