类:vm.SyntheticModule


🌐 Class: vm.SyntheticModule

稳定性: 1 - 实验性

此功能仅在启用 --experimental-vm-modules 命令标志时可用。

🌐 This feature is only available with the --experimental-vm-modules command flag enabled.

vm.SyntheticModule 类提供了 WebIDL 规范中定义的 合成模块记录。合成模块的目的是为将非 JavaScript 源暴露给 ECMAScript 模块图提供通用接口。

🌐 The vm.SyntheticModule class provides the Synthetic Module Record as defined in the WebIDL specification. The purpose of synthetic modules is to provide a generic interface for exposing non-JavaScript sources to ECMAScript module graphs.

import { SyntheticModule } from 'node:vm';

const source = '{ "a": 1 }';
const syntheticModule = new SyntheticModule(['default'], function() {
  const obj = JSON.parse(source);
  this.setExport('default', obj);
});

// Use `syntheticModule` in linking
(async () => {
  await syntheticModule.link(() => {});
  await syntheticModule.evaluate();

  console.log('Default export:', syntheticModule.namespace.default);
})();const { SyntheticModule } = require('node:vm');

const source = '{ "a": 1 }';
const syntheticModule = new SyntheticModule(['default'], function() {
  const obj = JSON.parse(source);
  this.setExport('default', obj);
});

// Use `syntheticModule` in linking
(async () => {
  await syntheticModule.link(() => {});
  await syntheticModule.evaluate();

  console.log('Default export:', syntheticModule.namespace.default);
})();