猫史档案馆


Require - 神岛客户端模块化模拟

用户:NomenNomen查看:0 回复:1 评论:0 创建时间:2024-03-07T10:48:51


好吧,没啥好讲的,因为这个东西实在是太简单了,只需要知道使用require就行

由于客户端目前没有模块化,所以可以先使用这个东西代替一下

需要注意的是,其他模块内的代码是无法访问当前作用域的,也就是说相当于一个独立地环境,并且客户端特性下,你也不能使用Date.now和Math.random这些函数,因为客户端有某些保护

直接上代码吧:

/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */

const { require } = requireFrom();


function requireFrom(_ = {
    /* Add your modules here */
}) {
    let modules = {};
    class Executable {
        static getExecutableString(str) {
            return `;const {module,require} = args;(function(){(${typeof str === "string" ? str : str.toString()})?.()})();return {module};`;
        }
        static createFunction(args, body) {
            return new Function(...args, body);
        }
        cache = null;
        exports = null;
        _module = {
            exports: {},
        };
        constructor(func) {
            this.module = Executable.getExecutableString(func);
        }
        getArgs({ module } = {}) {
            return {
                args: ["args"],
                content: {
                    module,
                    require
                }
            };
        }
        getModule() {
            return this._module;
        }
        exec() {
            if (this.cache) return this.cache;
            let result = Executable.createFunction(this.getArgs().args, this.module)(this.getArgs({
                module: this.getModule(),
            }).content);
            this.cache = result.module?.exports || {};
            return this.cache;
        }
    }
    function require(module) {
        if (modules[module]) {
            return modules[module].exec();
        }
        throw new Error(`Module ${module} not found`);
    }
    Object.keys(_).forEach((key) => {
        modules[key] = new Executable(_[key]);
    });
    return {
        require,
    };
}

 


回复

上一页1 页 / 共 1下一页
NomenNomen

示例代码:

const { require } = requireFrom();

require("./test1.js");

function requireFrom(_ = {
    /* Add your modules here */
    "./test1.js": function() {
        console.log("test1");
        console.log(require("./test2.js").output);
    },
    "./test2.js": function() {
        console.log("test2");
        module.exports.output = "test2";
    }
}) {
// ... something more

值得注意的是,除了const require那一行,其他内容都可以放置在文件任何位置,因为函数自动提升

点赞0


评论