Nodejs(下一步)无法从模块导入对象:找不到模块:无法解析 'fs'

Nodejs (Next) Cannot import object from module: Module not found: Can't resolve 'fs'

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

main.js(服务器文件)

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

...

const DR_LINK = "anything"

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

现在我需要一些路由器的应用程序对象。

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

它工作得很好。 但是当我尝试导入字符串 DR_LINK object

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}; 

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

我认为您混淆了服务器端和客户端代码。我的猜测是您正在尝试从服务器文件在客户端执行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