首页 > 解决方案 > electron "MAIN" : 要求你拥有 js 文件并从中调用函数

问题描述

我无法理解这里与电子有关的一些事情。我一直在寻找神奇的答案几个小时,但找不到任何东西。

我的目标很简单。我不希望我的主要 electron.js 文件有 5000 行长而没有任何组织,所以我试图将代码拆分为多个有意义的 js 文件。

我的想法是{ someFunction1, someFunction2 } from './scripts/someScript'在我的 electron.js 中使用 import,然后创建带有箭头函数的文件并导出它们。

然后我可以在主文件中调用我想要的函数。然而,这似乎是不可能的。我读过 electronjs 不支持 ES6 语法。我读过关于 Babel 的文章(但从我读到的内容来看,它意味着一堆额外的配置,我不想花几天时间尝试将它添加到已经被电子 + React 弄乱的一堆配置中(没有样板这里)。我没有找到这个组合的任何细节。

问题是。这在 2021 年可行吗?我错过了什么吗?你们会推荐什么?

文件看起来像这样:

import { someNodeModuleFunction } from 'someNodeModule';

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

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

export { someFunction1, someFunction2 }

编辑

这是我遇到问题的实际代码。我仍然得到

如果文件是 .js:“必须使用 import 来加载 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()

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

标签: javascriptnode.jsecmascript-6electronbabeljs

解决方案


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

例如:

import { someNodeModuleFunction } from 'someNodeModule';

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

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

module.exports = { someFunction1, someFunction2 }

使用您的模块:

const { someFunction1, someFunction2 } = require ('./FILE.js');

// ...

推荐阅读