Skip to content

Commit

Permalink
fix: 修复 require 路径错误
Browse files Browse the repository at this point in the history
  • Loading branch information
engsr6982 committed Dec 27, 2024
1 parent 1b3b02a commit 335bd2a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
11 changes: 10 additions & 1 deletion src/Manager/NodeManager.cc
Original file line number Diff line number Diff line change
Expand Up @@ -218,9 +218,18 @@ bool NodeManager::loadFile(EngineWrapper* wrapper, fs::path const& path) {
// Node.Js 22 的 ESM 和 16 写法不同、需查找16的写法
// clang-format off
string compiler = R"(
const PublicRequire = require('module').createRequire(`${process.cwd()}/ )" + dirname + R"( `);
const PublicRequire = require('module').createRequire(`)" + dirname + R"(`);
const PublicModule = require('module');
PublicModule.exports = {};
const fs = require('fs');
const path = require('path');
PublicModule.paths = [
//path.join(process.cwd(), 'plugins'), // plugins 目录
//path.resolve(` )"+dirname+R"( `), // 插件目录
//path.join(path.resolve(` )"+dirname+R"( `), 'node_modules') // 插件目录的 node_modules 目录
];
(function(exports, require, module, __filename, __dirname){ )" + js_code.value() + R"( })
({}, PublicRequire, PublicModule, ` )" +filename+ R"( `, ` )" +dirname+ R"( `);
)";
Expand Down
2 changes: 1 addition & 1 deletion test/package.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"main": "./test_js_plugin.js",
"main": "test_js_plugin.js",
"type": "commonjs"
}
13 changes: 11 additions & 2 deletions test/test_js_plugin.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
// / <reference path="./js_engine/dts/index.d.ts"/>

// /** @type {import("./js_engine/shortcutApi/JsonFileConfig.js")["default"]} */const JsonFileConfig = require("js_engine/lib/shortcutApi/JsonFileConfig.js");
console.log("Current working directory:", process.cwd());
console.log("Module paths:", module.paths);
console.log("__dirname:", __dirname);
console.log("__filename:", __filename);

try {
require("./js_engine/lib/shortcutApi/JsonFileConfig.js");
} catch (e) {
console.error("Failed to require JsonFileConfig:", e);
}

JSE.registerPlugin({
name: "test_js_plugin",
Expand Down Expand Up @@ -112,5 +121,5 @@ JSE.registerPlugin({
JSE.debug("sender: ", sender);
JSE.debug("sender.sendMessage: ", sender.sendMessage);
sender?.sendMessage("Hello: ", sender?.getName());
}
},
});

0 comments on commit 335bd2a

Please sign in to comment.