【问题标题】:Electron: Problem to import my own .js fileElectron:导入我自己的 .js 文件时出现问题
【发布时间】:2021-08-25 22:59:21
【问题描述】:

我正在发现 Electron,但我遇到了一个问题:我无法在我的 "test.js" 脚本中实现我的 "common.js" 文件.

这是我项目的架构:

rootProject
   -features(folder)
      -common.js
      -test.js
   -index.html

common.js

const hello = "hello";
module.exports = { hello };

test.js

const {hello} = require("./common.js");
console.log(hello);

index.html

<body>
  <h1>Hello World!</h1>
  <div class="flex-container">
    <span id="timeAfterRefreshGasFees"></span>
    <span id="rapid"></span>
    <span id="fast"></span>
    <span id="standard"></span>
    <span id="slow"></span>
  </div>
  <!-- You can also require other files to run in this process -->
  <script src="./renderer.js"></script>

  <!-- <script src="./features/common.js"></script> -->
  <script src="./features/test.js"></script>
</body>

在这种情况下,我得到:错误:找不到模块'./common.js'

如果我在 index.html 中取消注释

我想要一个 common.js 文件,我可以在其中放入一些东西(比如 const 等...)

我该如何解决?

我已经尝试了所有这些解决方案:Getting Unexpected Token Export

谢谢!

第一次解决后编辑:

我添加了这些行来获取 nodeIntegration

webPreferences: {
  nodeIntegration: true,
  contextIsolation: false,
  preload: path.join(__dirname, 'preload.js')
}

并删除了 common.js

中的 require 时出现此错误: 找不到模块“./common.js”

【问题讨论】:

    标签: javascript node.js module electron


    【解决方案1】:

    问题在于客户端 javacript 中不存在 require()

    一个更完善的答案:https://*.com/a/19059825/11224089

    【讨论】:

      【解决方案2】:

      就像@brunocordioli072 说的require 只是一个Node.js 函数,并且默认情况下Node.js 函数在Electron 中是禁用的。

      因为这是 Javascript,所以您可以使用 &lt;script&gt; 标记,就像您在包含文件时所做的那样。

      如果我在 index.html 中取消注释

      这是因为hello 已经在common.js 中定义,并且因为您在common.js 中包含&lt;script&gt; 标签,您已经可以在test.js 中使用它,而无需使用require


      旁注:

      如果您确实需要使用 require 或其他 Node.js 功能,您只需在 BrowserWindow 设置中打开 nodeIntegration 并关闭 contextIsolation,如下所示:

      new BrowserWindow({
          webPreferences:  {
              nodeIntegration:  true,
              contextIsolation: false
          },
      });
      

      但是,这会在您的应用中创建 security problems

      【讨论】:

      • 好的!谢谢您的回答。我知道如果我使用
      • 如果你像以前一样打开nodeIntegration,你可以使用require来导入NPM模块,但不能导入文件,所以require('./common.js')仍然无法工作。所以重新添加你的&lt;script&gt; 标签,现在nodeIntegration 已打开,你可以执行以下操作:require('fs')