javascript - Electron "MAIN": requiring you own js file and call function from it

标签 javascript node.js ecmascript-6 electron babeljs

我无法理解这里与 Electron 有关的一些事情。我一直在寻找神奇的答案几个小时,但找不到任何东西。
我的目标很简单。我不希望我的主要 electron.js 文件有 5000 行长而没有任何组织,所以我试图将代码拆分为多个有意义的 js 文件。
我的想法是使用 import { someFunction1, someFunction2 } from './scripts/someScript'在我的 electron.js 中,然后只使用其中的箭头函数创建该文件并导出它们。
然后我可以在主文件中调用我想要的函数。然而,这似乎是不可能的。我读过 electronjs 不支持 ES6 语法。我读过关于 Babel 的文章(但从我读到的内容来看,它意味着一堆额外的配置,我不想花几天时间尝试将它添加到已经被 Electron + React 弄乱的一堆配置中(没有样板这里)。我没有找到这个组合的任何细节。
问题是。这在 2021 年可行吗?我错过了什么吗?你们会推荐什么?
文件看起来像这样:

import { someNodeModuleFunction } from 'someNodeModule';

const someFunction1 = () => {
    return 1;
};

const someFunction2 = () => {
    return 2;
};

export { someFunction1, someFunction2 }

编辑
这是我遇到问题的实际代码。我仍然得到
如果文件是 .js:“必须使用导入来加载 ES 模块”
如果文件是 .mjs:“不能在模块外使用 import 语句”
这个脚本只是使用 fs 创建一个目录:
数据管理.mjs:
import { existsSync, mkdir } from 'fs';

const electron = require('electron');
const app = electron.app;

const documentFolder = app.getPath('documents');

const CreateDataDirectory = () => {
   const mainPath = documentFolder + 'AppName'
   if (!existsSync(mainPath)) {
      mkdir(mainPath);
   }
};

module.exports = { CreateDataDirectory } 
在 electron.js 中这样调用它:
const { CreateDataDirectory } = require('./scripts/DataManagement.mjs');

[...]

CreateDataDirectory()
不知道划分代码有多难。 :)

最佳答案

您可能需要使用 Node.js 模块语法( requiremodule.exports )或 Babel(代码转译器)。
例如:

import { someNodeModuleFunction } from 'someNodeModule';

const someFunction1 = () => {
    return 1;
};

const someFunction2 = () => {
    return 2;
};

module.exports = { someFunction1, someFunction2 }
使用您的模块:
const { someFunction1, someFunction2 } = require ('./FILE.js');

// ...

关于javascript - Electron "MAIN": requiring you own js file and call function from it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66344546/

相关文章:

node.js - centos服务器无法运行node express

javascript - 用于简化javascript中表达式的递归函数

android - nodejs可以服务android和ios吗

JavaScript `document.execCommand(' copy')` appears successful (returns ` true`), 但不向剪贴板写入任何内容

javascript - 如果这个 cookie !== null 则执行此操作

javascript - 用另一个 HTML 替换 HTML 标签

javascript - 单击按钮后清除输入字段

javascript - 在highcharts中传递Ajax数据组合图表

javascript - 确保 es6 find 在未定义属性时不会中断

javascript - 使用生成器暂停直到 promise 解决