在Electron中无法从渲染器中获取自定义模块

Ele*_*fee 6 javascript commonjs node.js ecmascript-6 electron

我正在尝试创建一些我可以导入的类,以便在我的项目中使用,但是我实际上在导入我正在制作的模块时遇到了一些麻烦.

我的文件结构如下所示:

??main.js
??src/
   ??html/
   ?  ??index.html
   ??css/
   ?  ??index.css
   ??js/
      ??index.js
      ??participant.js
Run Code Online (Sandbox Code Playgroud)

所有index.*文件彼此相关,因此具有相同的名称.

有问题的麻烦制造者是index.js,我的渲染器index.html,和participant.js

这是我得到的代码:

// index.js
const {Participant} = require("./participant");

const addNodeBtn = document.getElementById('add-node');

addNodeBtn.addEventListener('click', () => {
  // this is really just filler code to see if everything works
  let p = new Participant("Jason");
  alert(`His name was ${p.name}`);
});
Run Code Online (Sandbox Code Playgroud)

// participant.js
"use strict";

var Participant = class {
  constructor(name) {
    this.name = name;
  }
}

module.exports.Participant = Participant;
Run Code Online (Sandbox Code Playgroud)

无论出于何种原因,我不断收到错误"找不到模块./participant".

这是我尝试过的替代方案:

require("participant");
require("./participant.js");
module.exports = Participant;
module.exports.Participant = class { ... }
Run Code Online (Sandbox Code Playgroud)

一切都无济于事,都给了我同样的错误.我甚index.js至改名为其他东西,认为它与require机制发生了冲突.仍然没有变化.

有什么帮助解决这个问题?

更新它似乎在我的main.js文件中工作.

Arc*_*chy 3

事实证明,index.js一旦通过脚本标签包含在内,就会将其当前位置解析为包含 HTML 代码的位置。因此,要需要participant.js,考虑到您的文件夹结构,您将必须使用require('../js/participant.js'). 这仅影响使用该<script>标记的 HTML 页面中包含的脚本。所有其他require的将按预期工作。