簡體   English   中英

Nodejs(下一個)無法從模塊導入 object:找不到模塊:無法解析“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;

現在我的一些路由器需要應用程序 object。

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

沒有區別。 該應用程序始終導出,但字符串 object 不是。 這只發生在應用程序 object 以任何方式從服務器文件導出時。 通過刪除它,一切正常。

我認為您正在混淆服務器端和客戶端代碼。 我的猜測是您正在嘗試import {DR_LINK} from "../main"; 在客戶端從服務器文件。 線索是錯誤Module not found: Can't resolve 'fs' 這是因為fs是內置的 node.js(服務器端)package,所以你的前端不會知道它是什么。

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

您可以像這樣在下一個配置中定義環境變量:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM