【问题标题】:How to import node module with same name?如何导入同名的节点模块?
【发布时间】:2020-03-15 16:47:44
【问题描述】:

这是一个电子应用程序。我正在尝试导入 nodejs http 模块,但执行 require('http') 似乎会加载 stream-http 模块。使用它的地方可能存在依赖关系。我基本上是在尝试在电子应用程序中做http.createServer()。应用是这样设置的...

有一个BrowserWindow 与属性:webPreferences: { nodeIntegration: true, webSecurity: false, }。这个BrowserWindow 渲染器有一个反应组件,在构造函数的某处有这个语句:console.log(require('http')); 输出如下所示:

{request: ƒ, get: ƒ, ClientRequest: ƒ, IncomingMessage: ƒ, Agent: ƒ, …}
Agent: ƒ ()
ClientRequest: ƒ (opts)
IncomingMessage: ƒ (xhr, response, mode, fetchTimer)
METHODS: (26) ["CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LOCK", ...
get: ƒ (opts, cb)
globalAgent: push../node_modules/stream-http/index.js.http.Agent {}
request: ƒ (opts, cb)
__proto__: Object

基本上这是加载http-stream 模块。如何显式加载原始 nodejs http 模块?

额外问题:在开发者工具窗口中执行require('http') 会给我原始的nodejs http 模块。这是为什么呢?

【问题讨论】:

    标签: node.js reactjs electron require


    【解决方案1】:

    您是如何生成应用程序的?你在哪里需要你的“http”模块?

    请尝试根据本指南 https://electronjs.org/docs/tutorial/first-app#trying-this-example 设置您的应用程序。

    然后转到您的 main.js 文件并在上面做

    const server = require("http")
    console.log(server)
    

    我尝试了上述方法并正确获取了http服务器模块

    stream-http 是 Node 的浏览器原生 http 模块的实现。它试图尽可能地匹配 Node 的 API 和行为,但有些功能不可用,因为浏览器对请求的控制几乎没有。如果您错误地安装了它,请检查您的 package.json 并尝试将其删除。

    【讨论】:

    • 我的应用程序是用电子生成器生成的。 'http-stream' 不在 packages.json 中。 “http”模块是从渲染器进程导入的,而不是 main.js。节点“http”模块是否只能在主进程中使用?
    猜你喜欢
    • 2018-08-02
    • 2016-06-07
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多