V8中合成模块的默认导出

问题描述 投票:0回答:1

我想在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中使用合成模块时,是否可以设置默认导出?感谢您的提前答复。

c++ v8 embedded-v8
1个回答
0
投票

提示在错误消息中。错误消息是:

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));
      }
    );


© www.soinside.com 2019 - 2024. All rights reserved.