Files
squirrelVsis/js-beautify-wrapper-fixed.js
2025-09-17 11:28:54 +08:00

44 lines
1.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const fs = require('fs');
const path = require('path');
// 因为 js-beautify.js 直接在全局作用域定义 js_beautify
// 我们可以直接使用 require 来引入并获取函数
// 特别注意js-beautify.js 假设需要 window 或 global 对象
// Node.js 环境下,我们需要将 js_beautify 挂载到全局
let js_beautify;
// 读取并执行 js-beautify.js
const beautifyPath = path.join(__dirname, 'js-beautify.js');
const beautifyCode = fs.readFileSync(beautifyPath, 'utf-8');
// 创建一个安全的沙箱环境
global.window = global;
global.module = undefined;
global.exports = undefined;
// 执行代码
try {
eval(beautifyCode);
js_beautify = global.js_beautify;
} catch (error) {
console.error('加载 js-beautify.js 失败:', error);
throw error;
}
// 清理全局变量
delete global.window;
// 如果 js_beautify 没有挂载到 global尝试从 globalThis 获取
if (!js_beautify && globalThis.js_beautify) {
js_beautify = globalThis.js_beautify;
}
if (!js_beautify) {
throw new Error('无法从 js-beautify.js 中找到 js_beautify 函数');
}
module.exports = {
js_beautify: js_beautify
};