Electron 中的 ES 模块 (ESM)
🌐 ES Modules (ESM) in Electron
介绍
🌐 Introduction
ECMAScript 模块 (ESM) 格式是加载 JavaScript 包的标准方式 the standard way of loading JavaScript packages。
🌐 The ECMAScript module (ESM) format is the standard way of loading JavaScript packages.
Chromium 和 Node.js 各自实现了 ESM 规范,而 Electron 会根据上下文选择使用哪种模块加载器。
🌐 Chromium and Node.js have their own implementations of the ESM specification, and Electron chooses which module loader to use depending on the context.
本文档旨在概述 Electron 中 ESM 的限制,以及 Electron 中的 ESM 与 Node.js 和 Chromium 中 ESM 的差异。
🌐 This document serves to outline the limitations of ESM in Electron and the differences between ESM in Electron and ESM in Node.js and Chromium.
此功能是在 electron@28.0.0 中添加的。
🌐 This feature was added in electron@28.0.0.
摘要:ESM 支持矩阵
🌐 Summary: ESM support matrix
此表概述了支持 ESM 的位置以及使用的 ESM 加载程序。
🌐 This table gives a general overview of where ESM is supported and which ESM loader is used.
| 进程 | ESM 加载器 | 预加载中的 ESM 加载器 | 适用要求 |
|---|---|---|---|
| 主进程 | Node.js | 不适用 | |
| 渲染进程(沙盒模式) | Chromium | 不支持 | |
| 渲染进程(非沙盒 & 上下文隔离) | Chromium | Node.js | |
| 渲染进程(非沙盒 & 无上下文隔离) | Chromium | Node.js |
主进程
🌐 Main process
Electron 的主进程在 Node.js 环境中运行,并使用其 ESM 加载器。使用时应遵循Node 的 ESM 文档。要在主进程中的文件中启用 ESM,必须满足以下条件之一:
🌐 Electron's main process runs in a Node.js context and uses its ESM loader. Usage should follow Node's ESM documentation. To enable ESM in a file in the main process, one of the following conditions must be met:
- 该文件以
.mjs扩展名结尾 - 最近的父级 package.json 已设置
"type": "module"
请参阅 Node 的确定模块系统文档了解更多详情。
🌐 See Node's Determining Module System doc for more details.
注意事项
🌐 Caveats
你必须在应用的 ready 事件之前大量使用 await
🌐 You must use await generously before the app's ready event
ES 模块是异步加载的。这意味着只有来自主进程入口点导入的副作用会在 ready 事件之前执行。
🌐 ES Modules are loaded asynchronously. This means that only side effects
from the main process entry point's imports will execute before the ready event.
这是很重要的,因为某些 Electron API(例如 app.setPath)需要在应用的 ready 事件触发 之前 调用。
🌐 This is important because certain Electron APIs (e.g. app.setPath)
need to be called before the app's ready event is emitted.
在 Node.js ESM 中可以使用顶层的 await,确保对每个需要在 ready 事件之前执行的 Promise 进行 await。否则,你的应用可能会在代码执行前就被 ready。
🌐 With top-level await available in Node.js ESM, make sure to await every Promise that you need to
execute before the ready event. Otherwise, your app may be ready before your code executes.
对于动态 ESM 导入语句来说,这一点尤其重要(静态导入不受影响)。
例如,如果 index.mjs 在顶层调用 import('./set-up-paths.mjs'),那么在动态导入完成解析时,应用可能已经是 ready 了。
🌐 This is particularly important to keep in mind for dynamic ESM import statements (static imports are unaffected).
For example, if index.mjs calls import('./set-up-paths.mjs') at the top level, the app will
likely already be ready by the time that dynamic import resolves.
// add an await call here to guarantee that path setup will finish before `ready`
import('./set-up-paths.mjs')
app.whenReady().then(() => {
console.log('This code may execute before the above import')
})
JavaScript 转译器(如 Babel、TypeScript)在 Node.js 支持 ESM 导入之前,通常通过将这些调用转换为 CommonJS require 调用来支持 ES 模块语法。
🌐 JavaScript transpilers (e.g. Babel, TypeScript) have historically supported ES Module
syntax before Node.js supported ESM imports by turning these calls to CommonJS
🌐 The require calls.示例: @babel/plugin-transform-modules-commonjs
@babel/plugin-transform-modules-commonjs 插件会将 ESM 导入转换为 require 调用。具体语法将取决于 importInterop 设置。@babel/plugin-transform-modules-commonjs plugin will transform
ESM imports down to require calls. The exact syntax will depend on the
importInterop setting.import foo from "foo";
import { bar } from "bar";
foo;
bar;
// with "importInterop: node", compiles to ...
"use strict";
var _foo = require("foo");
var _bar = require("bar");
_foo;
_bar.bar;
这些 CommonJS 调用会同步加载模块代码。如果你正在将转译后的 CJS 代码迁移到原生 ESM,请注意 CJS 和 ESM 之间的时序差异。
🌐 These CommonJS calls load module code synchronously. If you are migrating transpiled CJS code to native ESM, be careful about the timing differences between CJS and ESM.
渲染器进程
🌐 Renderer process
Electron 的渲染进程在 Chromium 环境中运行,并将使用 Chromium 的 ESM 加载器。实际上,这意味着 import 语句:
🌐 Electron's renderer processes run in a Chromium context and will use Chromium's ESM loader.
In practice, this means that import statements:
- 将无法访问 Node.js 内置模块
- 将无法从
node_modules加载 npm 包
<script type="module">
import { exists } from 'node:fs' // ❌ will not work!
</script>
如果你希望通过 npm 直接在渲染进程中加载 JavaScript 包,我们建议使用诸如 webpack 或 Vite 之类的打包工具,将你的代码编译为用于客户端的格式。
🌐 If you wish to load JavaScript packages via npm directly into the renderer process, we recommend using a bundler such as webpack or Vite to compile your code for client-side consumption.
预加载脚本
🌐 Preload scripts
渲染器的预加载脚本将在 可用时 使用 Node.js ESM 加载器。ESM 的可用性取决于其渲染器的 sandbox 和 contextIsolation 偏好设置的值,并且由于 ESM 加载的异步特性,还存在一些其他注意事项。
🌐 A renderer's preload script will use the Node.js ESM loader when available.
ESM availability will depend on the values of its renderer's sandbox and contextIsolation
preferences, and comes with a few other caveats due to the asynchronous nature of ESM loading.
注意事项
🌐 Caveats
ESM 预加载脚本必须具有 .mjs 扩展名
🌐 ESM preload scripts must have the .mjs extension
预加载脚本会忽略 "type": "module" 字段,因此你 必须 在 ESM 预加载脚本中使用 .mjs 文件扩展名。
🌐 Preload scripts will ignore "type": "module" fields, so you must use the .mjs file
extension in your ESM preload scripts.
沙盒预加载脚本无法使用 ESM 导入
🌐 Sandboxed preload scripts can't use ESM imports
沙盒预加载脚本以普通 JavaScript 运行,不带 ESM 上下文。如果需要使用外部模块,建议为你的预加载代码使用打包工具。加载 electron API 仍然通过 require('electron') 完成。
🌐 Sandboxed preload scripts are run as plain JavaScript without an ESM context. If you need to
use external modules, we recommend using a bundler for your preload code. Loading the
electron API is still done via require('electron').
有关沙箱的更多信息,请参阅 进程沙箱 文档。
🌐 For more information on sandboxing, see the Process Sandboxing docs.
未沙盒的 ESM 预加载脚本将在页面加载后在没有内容的页面上运行
🌐 Unsandboxed ESM preload scripts will run after page load on pages with no content
如果渲染器加载页面的响应体完全为空(即 Content-Length: 0),其预加载脚本将不会阻塞页面加载,这可能导致竞态条件。
🌐 If the response body for a renderer's loaded page is completely empty (i.e. Content-Length: 0),
its preload script will not block the page load, which may result in race conditions.
If this impacts you, change your response body to have something in it
(e.g. an empty html tag (<html></html>)) or swap back to using a CommonJS preload script
(.js or .cjs), which will block the page load.
ESM 预加载脚本必须进行上下文隔离才能使用动态 Node.js ESM 导入
🌐 ESM preload scripts must be context isolated to use dynamic Node.js ESM imports
如果你的非沙箱渲染器进程没有启用 contextIsolation 标志,你将无法通过 Node 的 ESM 加载器动态 import() 文件。
🌐 If your unsandboxed renderer process does not have the contextIsolation flag enabled,
you cannot dynamically import() files via Node's ESM loader.
// ❌ these won't work without context isolation
const fs = await import('node:fs')
await import('./foo')
这是因为 Chromium 的动态 ESM import() 函数通常在渲染进程中优先执行,并且在没有上下文隔离的情况下,无法知道 Node.js 是否可以在动态导入语句中使用。如果启用上下文隔离,来自渲染器隔离预加载上下文的 import() 语句可以被路由到 Node.js 模块加载器。
🌐 This is because Chromium's dynamic ESM import() function usually takes precedence in the
renderer process and without context isolation, there is no way of knowing if Node.js is available
in a dynamic import statement. If you enable context isolation, import() statements
from the renderer's isolated preload context can be routed to the Node.js module loader.