[英]Nodejs (Next) Cannot import object from module: Module not found: Can't resolve 'fs'
I have nodejs app using react and nextjs.我有使用 react 和 nextjs 的 nodejs 应用程序。 The most important pieces of the app are kept in the server file.应用程序最重要的部分保存在服务器文件中。
main.js (server file) main.js (服务器文件)
const app = next({ dev }) //dev = true
...
const DR_LINK = "anything"
module.exports.app = app;
module.exports.DR_LINK = DR_LINK;
Now I need the app object for some of my routers.现在我的一些路由器需要应用程序 object。
//any router file
const {app} = require("../main")
And it works perfectly fine.它工作得很好。 But when I try to import the string DR_LINK object但是当我尝试导入字符串 DR_LINK object
import {DR_LINK} from "../main";
//not in the same file as the import for app
I get this error我收到这个错误
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
The export order or exporting it like出口订单或出口它喜欢
module.exports = { app, DR_LINK};
makes not difference.没有区别。 The app is allways exported but the string object is not.该应用程序始终导出,但字符串 object 不是。 This only happens when app object is exported in any way from the server file.这只发生在应用程序 object 以任何方式从服务器文件导出时。 By removing it, everything works fine.通过删除它,一切正常。
I think you are mixing up server side and client side code.我认为您正在混淆服务器端和客户端代码。 My guess is you are trying to do import {DR_LINK} from "../main";
我的猜测是您正在尝试import {DR_LINK} from "../main";
on client side from a server file.在客户端从服务器文件。 The clue is the error Module not found: Can't resolve 'fs'
.线索是错误Module not found: Can't resolve 'fs'
。 This is because fs
is a built in node.js (server side) package, so your frontend will not know what it is.这是因为fs
是内置的 node.js(服务器端)package,所以你的前端不会知道它是什么。
I suspect your router files are still server side, hence why the imports (require) work there.我怀疑您的路由器文件仍然在服务器端,因此导入(需要)在那里工作。
You can define env variables inside next config like so:您可以像这样在下一个配置中定义环境变量:
https://nextjs.org/docs/api-reference/next.config.js/environment-variables https://nextjs.org/docs/api-reference/next.config.js/environment-variables
Or maybe this could also be an option for you as well:或者,这也可能是您的一个选择:
https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser https://nextjs.org/docs/basic-features/environment-variables#exposing-environment-variables-to-the-browser
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.