【发布时间】:2021-04-03 03:27:54
【问题描述】:
当我的视图加载时,我试图在getInitialProps 中获取已解析文件的内容,问题是它告诉我Module not found: Can't resolve 'fs',我不明白为什么 - 根据文档,@987654321 @。
我的 API 路由:
import parseCommands, { ICommands } from "../../modules/parser/json";
export const getCommands = (): ICommands => {
const commands = parseCommands("data.json");
return commands;
};
我的反应观点:
import { NextPage } from "next";
import { getCommands } from "../../pages/api/commands";
import { ICommands } from "../../modules/parser/json";
import styles from "./commands.module.scss";
type Props = {
commands: ICommands;
};
const Commands:NextPage<Props> = ({ commands }) => {
return (
<div className={styles.wrapper}>
{commands}
</div>
);
};
Commands.getInitialProps = async () => {
const commands:ICommands = await getCommands();
return {
commands
};
};
export default Commands;
我的文件试图导入模块“fs”:
import fs from "fs";
[...]
const parseCommands = (path: string): ICommands => {
const file:string = fs.readFileSync(path, "utf8");
const json:any = JSON.parse(file);
const commands:ICommands = parseData(json);
return commands;
};
export default parseCommands;
我做错了什么?
【问题讨论】:
-
在前端等待
fs,不可能,SSR知道是服务端渲染,而不是服务端操作,这就是为什么你不能在react或next中执行任何服务端的事情 -
@Nisharg Shah 实际上,在 Next.js 中,您可以执行服务器端渲染。
-
这能回答你的问题吗? How Do I use a node.js module with Next.js?
标签: reactjs typescript next.js