【问题标题】:how to solve the error that fs module is not found when used react and next.js使用react和next.js时找不到fs模块的错误如何解决
【发布时间】:2018-11-22 15:25:25
【问题描述】:

我正在使用没有路由器设置的反应应用程序。我想构建我的 sitemap.xml 文件。我尝试了一些模块,如 sitemap.js、react-router-sitemap、sitemap-generator。但是这些模块由于 fs 模块丢失而引发错误。我通过npm install --save 安装了 fs 模块。但它仍然显示错误。

我在一些论坛上找到在 webpack.config 文件中添加以下代码。

节点:{ fs:“空” } 我不确定这个文件在哪里。我在站点地图相关模块中找不到它们。

请帮我解决这个问题。我是新手。

这是我的文件夹结构。

【问题讨论】:

  • React 是一个前端库。 fs 是后端文件系统节点库。你想在 React 的前端做 fs 的东西吗?请添加您到目前为止所做的相关最小代码。
  • 我没有使用 fs 模块。但我可以找到 const fs = require('fs');在站点地图生成器模块内。我使用 fs 模块在上面列出的站点地图生成模块
  • 是的,但是那些站点地图库使用fs 模块。如果您尝试在前端文件中使用它们,那么它们将尝试在浏览器中运行,您将收到该错误消息。使用其中一个模块时,您尝试在哪些文件中制作站点地图?
  • 好的,这就是问题所在。 index.js 中的代码最终会在客户端、浏览器中运行。您使用的那些节点模块(如sitemap.js)是服务器端模块。设计为在后端运行。你需要在那里运行它们。做一些关于前端与后端 webapp 开发的研究,特别是在 Node.js 中。这应该有助于澄清你的理解
  • 我不确定这个问题的确切含义,或者它与问题的关系。是的,您可以直接调用这些模块,但只能在 后端 环境中调用。再一次,看看我所说的,这应该有助于澄清事情。

标签: node.js reactjs next.js


【解决方案1】:

创建 next.config.js 并放入以下代码。对我来说效果很好。

next.config.js

module.exports = {
    webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
      // Note: we provide webpack above so you should not `require` it
      // Perform customizations to webpack config
      // Important: return the modified config

      // Example using webpack option
      //config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
      config.node = {fs:"empty"}
      return config
    },
    webpackDevMiddleware: config => {
      // Perform customizations to webpack dev middleware config
      // Important: return the modified config
      return config
    },
  }

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2019-09-10
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多