使用 PHP V8JS 渲染 javascript 时出现问题

Problem when rendering javascript with PHP V8JS

我有这段代码可以使用 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 API and this post)。

你可以这样做:

$v8 = new V8Js();
$v8->setModuleLoader(function($path) {
    return file_get_contents($path);
});

当然,您需要调整代码以从正确的目录加载文件。