gpt4 book ai didi

electron - 将我自己的文件导入到 Electron 渲染器进程中

转载 作者:行者123 更新时间:2023-12-03 12:28:19 26 4
gpt4 key购买 nike

这看起来真的很愚蠢,但我需要帮助将一些源代码导入到 Electron 的渲染器进程中:

我有一个 Electron 应用程序:
index.html(加载带有标签的 window.js)
- index.js
- 窗口.js
- 有用的函数.js

window.js , 我想从 useful_functions.js 导入一些函数,所以我尝试了以下方法:

// fails with: Uncaught SyntaxError: Unexpected identifier
import { very_useful } from './useful_functions.js';

// fails with: Uncaught ReferenceError: require is not defined
const { very_useful } = require('./useful_functions.js');

// fails with: Uncaught ReferenceError: require is not defined
require('electron').remote.require('./useful_functions.js')

我也试过 nodeIntegration标志,但这也无济于事

备注 :我不是要导入 npm 模块,而是我自己的代码,在它旁边的另一个文件中。

我正在寻找示例,但我只找到只有基本文件的超小样本。 (或者像 atom 这样的大型应用程序需要我一段时间才能弄清楚)

我还没有为这个项目设置 webpack,但我确信有一种更简单的方法来完成这个非常基本的任务......

谢谢你的帮助。

最佳答案

index.html , 使用 require()而不是加载 window.js带有标签,即替换:

<script src="window.js"></script>

和:
<script>require('./window.js');</script>

然后,在 window.js ,以下语句也应该起作用:
const { very_useful } = require('./useful_functions.js');

请注意 nodeIntegration: true在传递给 new BrowserWindow() 的选项中需要反正:
webPreferences:
{
nodeIntegration: true
}

看:
  • Node Modules

  • Functions and objects are added to the root of a module by specifying additional properties on the special exports object.

    Variables local to the module will be private, because the module is wrapped in a function by Node.js (see module wrapper).


  • Module Wrapper

  • Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:

    (function(exports, require, module, __filename, __dirname) {
    // Module code actually lives in here
    });

    关于electron - 将我自己的文件导入到 Electron 渲染器进程中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57829933/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com