ts命名空间合并

在用ts 开发游戏的时候,发现命名空间使用比较不友好,需要文件引入以及使用声明文件.d.ts才能做到很好的代码提示,但是在复杂类设计的情况下.d.ts书写起来也比较费劲,于是开始研究怎么才能做到用命名空间隔离作用域并且能够有很好的使用体验。当前主要实现方式是挂载在windows底下,并且将同命名空间下的对象合并,来达到效果,效果比较理想。上代码:

//UIMgr.ts文件实现 
/*
 * @author: huangww
 * @Date: 2021-03-08 17:16:30
 * @LastEditTime: 2021-03-08 17:42:48
 * @FilePath: \ept\assets\Script\core\UIMgr.ts
 */
 namespace core {
    class UIMgr {
        /**测试UI */
        test() {
            console.log("UI TEST");
        }
    }
    export const ui = new UIMgr();
}
if (!window["core"]) {
    window["core"] = core;
} else {
    Object.assign(window["core"], core);
}

//EventMgr.ts文件实现 
/*
 * @author: huangww
 * @Date: 2021-03-08 17:16:39
 * @LastEditTime: 2021-03-08 17:44:21
 * @FilePath: \ept\assets\Script\core\EventMgr.ts
 */
namespace core {
    /**全局变量跨文件使用测试 */
    export const test = {
        test: function () {
            core.ui.test();
        },
    };

    /**事件测试类 */
    class EventMgr {
        //test
        test() {
            console.log("EVENT TEST");
        }
    }
    /**
     *事件测试类实例
     */
    export const event = new EventMgr();
}
if (!window["core"]) {
    window["core"] = core;
} else {
    Object.assign(window["core"], core);
}

在代码中即可直接使用core全局对象来访问

core.event.test();core.test.test();
core.ui.test();
core .event.test():

This article was updated on 十月 10, 2023