如何在Node.js中实现类似浏览器window的全局对象共享功能
在Node.js中实现类似浏览器全局对象的跨模块共享
问题描述
我在项目的/foo目录下定义了classPerson类,需要在./bar目录中使用它,但bar目录不允许直接从foo导入。在浏览器环境中我是这么实现的:
/foo目录代码:
const classPerson = new classPerson(); Object.assign(window, { classPerson });
/bar目录代码:
const person = window.classPerson;
现在要在Node.js中实现类似功能,但Node.js没有window对象,该怎么做?
解决方案
1. 用global对象(CommonJS环境)
Node.js的CommonJS模块系统里有global全局对象,作用和浏览器的window类似,直接把需要共享的实例挂载上去就行:
/foo目录代码:
// 先定义classPerson类 class classPerson { // 类的具体实现 } const personInstance = new classPerson(); // 挂载到global global.classPerson = personInstance;
/bar目录代码:
const person = global.classPerson;
注意:如果你的项目用的是ES模块(ESM),
global会被globalThis替代,看下面的方案。
2. 用globalThis(通用跨环境方案)
globalThis是ES2020标准的全局对象,Node.js v12+和浏览器都支持,是更通用的写法:
/foo目录代码:
class classPerson { // 类的具体实现 } const personInstance = new classPerson(); globalThis.classPerson = personInstance;
/bar目录代码:
const person = globalThis.classPerson;
3. 利用模块缓存(更规范的无全局污染方案)
如果不想用全局对象,还可以靠Node.js的模块缓存机制实现。在项目根目录建一个公共中转文件,让bar导入这个文件来间接获取实例:
根目录globals.js:
module.exports = require('../foo/classPerson').personInstance;
/foo目录classPerson.js:
class classPerson { // 类的具体实现 } const personInstance = new classPerson(); module.exports = { personInstance };
/bar目录代码:
const person = require('../../globals');
这种方式不会造成全局污染,也更符合Node.js的模块规范,推荐在大型项目里用。
内容的提问来源于stack exchange,提问作者YTG
相关产品推荐
相关产品推荐

