【问题标题】:Nodejs (Next) Cannot import object from module: Module not found: Can't resolve 'fs'Nodejs(下一个)无法从模块导入对象:找不到模块:无法解析“fs”
【发布时间】:2022-01-29 17:05:17
【问题描述】:

我有使用 react 和 nextjs 的 nodejs 应用程序。应用程序最重要的部分保存在服务器文件中。

ma​​in.js(服务器文件)

const app = next({ dev }) //dev = true

...

const DR_LINK = "anything"

module.exports.app = app;
module.exports.DR_LINK = DR_LINK;

现在我需要一些路由器的 app 对象。

//any router file
const {app} = require("../main")

而且它工作得非常好。 但是当我尝试导入字符串 DR_LINK 对象时

import {DR_LINK} from "../main"; 
//not in the same file as the import for app

我收到此错误

error - ./node_modules/destroy/index.js:14:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/send/index.js
./node_modules/express/lib/response.js
./node_modules/express/lib/express.js
./node_modules/express/index.js
./main.js
./components/CreateForm.js
./pages/create.js

https://nextjs.org/docs/messages/module-not-found
error - unhandledRejection: OverwriteModelError: Cannot overwrite `Declaration` model once compiled.
//for some reason it affects the db models too

导出订单或导出之类的

module.exports = { app, DR_LINK}; 

没有区别。应用程序总是被导出,但字符串对象不是。这仅在以任何方式从服务器文件导出应用程序对象时发生。通过删除它,一切正常。

【问题讨论】:

  • 您能否显示您要导入的文件的完整代码DR_LINK
  • 您的某个软件包似乎依赖于它无法找到的 fs。试试npm installnpm ci

标签: node.js next.js node-modules module.exports


【解决方案1】:

我认为您正在混淆服务器端和客户端代码。我的猜测是您正在尝试从服务器文件在客户端执行import {DR_LINK} from "../main";。线索是错误Module not found: Can't resolve 'fs'。这是因为fs 是一个内置的node.js(服务器端)包,所以你的前端不会知道它是什么。

我怀疑您的路由器文件仍然在服务器端,因此导入(需要)在那里工作。

您可以像这样在下一个配置中定义环境变量:

https://nextjs.org/docs/api-reference/next.config.js/environment-variables

或者这也可能是您的一个选择:

https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser

【讨论】:

    猜你喜欢
    • 2022-06-27
    • 1970-01-01
    • 2018-06-29
    • 2021-08-01
    • 2022-08-05
    • 2019-12-01
    • 2019-05-31
    • 2020-02-24
    相关资源
    最近更新 更多