ES6 语法导入 Electron (require..)

2022-01-10 00:00:00 import electron javascript ecmascript-6

为了学习新的 ES6 语法,我一直在尝试重构一些 JS 代码.

To learn the new ES6 syntax, I've been trying to refactor some JS code.

我对整个导入/导出方法感到非常困惑.

I'm absolutely confused though by the whole import / export methods.

如何将这个 require 语句改成 ES6?

How do I change this require statement into ES6?

var remote = require('electron').remote

我看过这个答案但是:

  1. 它不起作用
  2. 看起来并没有太多 ES6 风格

有什么想法吗?

推荐答案

似乎在 Node 6 或 Chrome 51 中 导入都没有实现,所以 Electron 也不支持它们,根据这篇文章:https://discuss.atom.io/t/does-electron-support-es6/19366/18

It seems imports are not implemented in either Node 6 or Chrome 51 so Electron also does not support them, according to this post: https://discuss.atom.io/t/does-electron-support-es6/19366/18

最后一个电子文档也不使用导入,它们使用 destructuring 语法:

And also the last electron doc doesn't use imports, they use destructuring syntax:

const { BrowserWindow } = require('electron').remote
// or
const { remote } = require('electron')
const { BrowserWindow } = remote

http://electron.atom.io/docs/api/remote/

但是你可以使用带有 require 钩子的 babel:http://babeljs.io/docs/usage/require/

But you can use babel with the require hook: http://babeljs.io/docs/usage/require/

自动编译每个必需的模块,以便您可以使用导入.当然,给电子的脚本(需要 babel 的脚本)没有编译,所以你需要做一个引导程序:

To be auto compile each required modules so you will be able to use imports. Of course the script given to electron (the one that require babel) is not compiled so you need to make a bootstrap:

// bootwithbabel.js
require("babel-register");
require( process.argv.splice(2) );

在外壳(sh)中:

electron bootwithbabel.js app.es
alias electrones="electron bootwithbabel.js "
electrones coron.es // ^^

然后你可以在你的应用中写:

Then in your app you can then write:

import electron from 'electron';
import { remote } from 'electron';

你也可以只导入远程模块:

You can also import only the remote module:

import { remote } from 'electron';

但你只能在一个语句中同时导入:

But you can only import both in one statement:

import electron, { remote } from 'electron'

electron.ipcRenderer.on();
let win = new remote.BrowserWindow({width: 800, height: 600});
remote.getGlobal(name)

游乐场

相关文章