javascript - 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()
不知道划分代码有多难。:)
解决方案
您可能需要使用 Node.js 模块语法 ( require
and 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');
// ...
推荐阅读
- c++ - 项目中的排序算法实现
- javascript - koa 中的 koa-router 路由错误
- reactjs - 为什么我不能使用 useState React Hook 更新状态,“警告:无法对未安装的组件执行 React 状态更新。这是一个无操作,但我”
- linux - 在 for 循环中同时使用基本名称和绝对路径
- google-sheets - VLOOKUP 返回一个范围内的错误值
- python - 是否可以在两条烧瓶路线之间创建一个警报框?
- python-3.x - 如何解决 Socket.IO Django 框架中的 401 Unauthorized 错误?
- assembly - GCD通过重复减法太慢
- python - 尝试通过 python 套接字升级到 http2
- java - 尝试进行交易时从验证器获取有关公钥长度的异常