【问题标题】:Can't use 'fs' in getInitialProps不能在 getInitialProps 中使用“fs”
【发布时间】: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


【解决方案1】:

getInitialProps 在服务器端和客户端都运行,因此不能在没有分支的情况下使用fs。请改用getServerSideProps

你可以用 Or 的回答来解决这个模块,但这只是解决问题。

或者,您可以在getInitialProps 中进行分支,以确定我们是否在服务器上执行代码。您不应在 Web 服务器代码中使用 readFileSync


export const getInitialProps = async ({ req }) => {
  if (res === undefined) {
    return { commands: [] }
  }

  const fs = await import('fs')
  const readFile = fs.promises.readFile;
  return { commands: await readFile(...) }
}

【讨论】:

    【解决方案2】:

    你需要更新你的 next.js 版本 - Update for modern Next.js (9.4+)

    您可能还需要创建一个包含以下内容的 next.config.js 文件来构建客户端包:

    module.exports = {
      webpack: (config, { isServer }) => {
        // Fixes npm packages that depend on `fs` module
        if (!isServer) {
          config.node = {
            fs: 'empty'
          }
        }
    
        return config
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 2021-10-19
      • 2015-01-04
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-13
      • 2020-03-07
      相关资源
      最近更新 更多