我有这段代码可以使用PHP和V8JS呈现javascript代码,但无法正常工作。有人知道问题出在哪里吗?

<?php

$v8 = new V8Js();
$code = file_get_contents('index2.js');
$result = $v8->executeString( $code );
var_dump($result);
?>
index2.js
const jsdom = require('jsdom');
const { JSDOM } = jsdom;

const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"
发生的错误:
Fatal error: Uncaught V8JsScriptException: V8Js::compileString():1: No module loader in index.php on line 6
我想象问题出在需要节点模块jsdom

最佳答案

为了需要一个模块,必须使用setModuleLoader()注册一个模块加载器(请参阅V8Js APIthis post)。
您可以执行以下操作:

$v8 = new V8Js();
$v8->setModuleLoader(function($path) {
    return file_get_contents($path);
});
当然,您将需要调整代码以从正确的目录加载文件。

10-06 00:32