【问题标题】:electron "MAIN" : requiring you own js file and call function from itelectron "MAIN" : 要求你拥有 js 文件并从中调用函数
【发布时间】:2021-05-26 09:33:12
【问题描述】:

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

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

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

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

问题是。这在 2021 年可行吗?我错过了什么吗?大家有什么推荐的?

文件看起来像这样:

import { someNodeModuleFunction } from 'someNodeModule';

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

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

export { someFunction1, someFunction2 }

编辑

这是我遇到问题的实际代码。我还是得到了

如果文件是 .js:“必须使用 import 来加载 ES 模块” 如果文件是 .mjs: "Cannot use import statement outside a module"

这个脚本只是简单地使用 fs 创建一个目录:

DataManagement.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()

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

【问题讨论】:

    标签: javascript node.js ecmascript-6 electron babeljs


    【解决方案1】:

    您可能需要使用 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');
    
    // ...
    

    【讨论】:

    • 抱歉这么晚才回复。我已经尝试过了,但无法让它工作。我将使用实际代码和我得到的确切错误消息更新代码。
    • 这确实有效。只是意识到我在这里使用 mkdir 是错误的。它仍然帮助我实现了权利。谢谢。
    【解决方案2】:

    你可以使用module.exports:

    otherModule.js

    const someFunction1 = () => {
        return 1;
    };
    
    const someFunction2 = () => {
        return 2;
    };
    
    module.exports = {
        someFunction1,
        someFunction2
    };
    

    main.js

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

    【讨论】:

      猜你喜欢
      • 2016-06-13
      • 2013-03-15
      • 2018-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      相关资源
      最近更新 更多