Namespace a dynamically loaded javascript file's contents

邮差的信 提交于 2019-12-03 06:21:24

Yes, CommonJS Modules/1.1 specifies only one way of doing it.

I've used it only with Node.js on server side, but I believe there are other libraries created to work with browser that are CommonJS compliant. Beware that there are multiple module specifications for server/browser (didn't dig into that yet).

Modules are written just like any other piece of javascript, the only addition is you export what you want to expose:

module.exports.bar = Bar;

function Bar() {
 // code
}

And the usage:

var foo = require('mymodule');

foo.bar();

What is actually done in the background, the whole code is wrapped into another function and exports are its properties.

Also, Michael Bolin talked about similar problem in his talk about 'with' keyword at JSConf.

If you mean to add a namespace to everything that is defined in that file while loading it dynamically, without modifying the file itself, the answer is no.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!