V8 中合成模块的默认导出
Default export for synthetic module in V8
我想在 V8 中使用合成模块的默认导出。我有 synthetic_module
,一个将 C++ 函数暴露给 JS 的模块,代码如下:
Local<String> txt = String::NewFromUtf8(isolate, u8R"(
import defaultFoo from './myModule.js';
defaultFoo();
").ToLocalChecked();
...
ScriptCompiler::Source src(txt, origin);
static Local<Module> module
= ScriptCompiler::CompileModule(isolate, &src).ToLocalChecked();
// module->GetStatus() is kUninstantiated here
module->InstantiateModule(context,
[](Local<Context> context,
Local<String> specifier,
Local<Module> referrer) -> MaybeLocal<Module> {
return synthetic_module;
});
// module->GetStatus() is still kUninstantiated
// if synthetic_module does not have default export
使用 v8::TryCatch
,我可以获得 SyntaxError
synthetic_module
没有默认导出。在 V8 中使用合成模块时有没有办法设置默认导出?提前感谢您的回答。
提示在错误消息中。错误消息是:
SyntaxError: The requested module './myModule.js' does not provide an export named 'default'
因此,要设置默认导出,我可以像这样使用名称 "default"
进行导出。
Local<Module> synthetic_module
= Module::CreateSyntheticModule(
isolate,
String::NewFromUtf8(isolate, "Synthetic").ToLocalChecked(),
{ String::NewFromUtf8(isolate, "default").ToLocalChecked(), ... },
[](Local<Context> context, Local<Module> module) -> MaybeLocal<Value> {
auto isolate = context->GetIsolate();
module->SetSyntheticModuleExport(
String::NewFromUtf8(isolate, "default").ToLocalChecked(),
Function::New(context, ...)
);
return MaybeLocal<Value>(True(isolate));
}
);
我想在 V8 中使用合成模块的默认导出。我有 synthetic_module
,一个将 C++ 函数暴露给 JS 的模块,代码如下:
Local<String> txt = String::NewFromUtf8(isolate, u8R"(
import defaultFoo from './myModule.js';
defaultFoo();
").ToLocalChecked();
...
ScriptCompiler::Source src(txt, origin);
static Local<Module> module
= ScriptCompiler::CompileModule(isolate, &src).ToLocalChecked();
// module->GetStatus() is kUninstantiated here
module->InstantiateModule(context,
[](Local<Context> context,
Local<String> specifier,
Local<Module> referrer) -> MaybeLocal<Module> {
return synthetic_module;
});
// module->GetStatus() is still kUninstantiated
// if synthetic_module does not have default export
使用 v8::TryCatch
,我可以获得 SyntaxError
synthetic_module
没有默认导出。在 V8 中使用合成模块时有没有办法设置默认导出?提前感谢您的回答。
提示在错误消息中。错误消息是:
SyntaxError: The requested module './myModule.js' does not provide an export named 'default'
因此,要设置默认导出,我可以像这样使用名称 "default"
进行导出。
Local<Module> synthetic_module
= Module::CreateSyntheticModule(
isolate,
String::NewFromUtf8(isolate, "Synthetic").ToLocalChecked(),
{ String::NewFromUtf8(isolate, "default").ToLocalChecked(), ... },
[](Local<Context> context, Local<Module> module) -> MaybeLocal<Value> {
auto isolate = context->GetIsolate();
module->SetSyntheticModuleExport(
String::NewFromUtf8(isolate, "default").ToLocalChecked(),
Function::New(context, ...)
);
return MaybeLocal<Value>(True(isolate));
}
);