我在我的(Windows桌面)C++应用程序中使用了嵌入式V8引擎。我知道V8支持ES6模块,那么我该如何在我的应用程序中启用和使用这个功能呢?
我不希望有人提供完整的示例,但是提供一个高层次的答案指引我(以及未来的读者)朝着正确的方向前进就可以满足我的期望。
我在我的(Windows桌面)C++应用程序中使用了嵌入式V8引擎。我知道V8支持ES6模块,那么我该如何在我的应用程序中启用和使用这个功能呢?
我不希望有人提供完整的示例,但是提供一个高层次的答案指引我(以及未来的读者)朝着正确的方向前进就可以满足我的期望。
以下是一个实际例子,由于我曾打算在某个时间点编写一些实际示例,因此没有来得及提供V8的实际示例。如果需要了解使用示例,建议参考Node.js的实现、或我的实现,两者的布局非常相似(都是由同一批人员编写)。同时,D8,V8的CLI调试器也有一种实现。
Local<String> source_text = String::NewFromUtf8(
isolate, "import 'some thing'; 1 + 1");
ScriptOrigin origin(String::NewFromUtf8("main.mjs"), // specifier
Integer::New(isolate, 0), // line offset
Integer::New(isolate, 0), // column offset
False(isolate), // is cross origin
Local<Integer>(), // script id
Local<Value>(), // source map URL
False(isolate), // is opaque
False(isolate), // is WASM
True(isolate)); // is ES6 module
Context::Scope context_scope(context);
ScriptCompiler::Source source(source_text, origin);
Local<Module> module;
if (!ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) {
// if you have a v8::TryCatch, you should check it here.
return;
}
// You can resolve import requests ahead of time (useful for async)
for (int i = 0; i < module->GetModuleRequestsLength(); i++) {
Local<String> specifier = module->GetModuleRequest(i); // "some thing"
}
// or you can resolve them sync in the InstantiateModule callback
module->InstantiateModule(context, [](Local<Context> context, // "main.mjs"
Local<String> specifier, // "some thing"
Local<Module> referrer) {
return Local<Module>();
});
// setting this callback enables dynamic import
isolate->SetImportModuleDynamicallyCallback([](Local<Context> context,
Local<ScriptOrModule> referrer,
Local<String> specifier) {
return MaybeLocal<Promise>();
});
// setting this callback enables import.meta
isolate->SetHostInitializeImportMetaObjectCallback([](Local<Context> context,
Local<Module> module,
Local<Object> meta) {
// meta->Set(key, value); you could set import.meta.url here
});
Local<Value> result;
if (module->Evaluate(context).ToLocal(&result)) {
String::Utf8Value utf8(isolate, result);
printf("module eval result: %s\n", *utf8);
} else {
// once again, if you have a v8::TryCatch, use it here.
}
import
请求吗?您需要遍历ModuleRequests中的所有specifier,但是我不知道下一步该怎么做。我应该如何告诉V8将此模块链接到那个specifier? - Cisco Ortega
import {x} from "./y.js";
我认为V8不会知道在哪里查找y.js
。 - Boinst