开发者

How to reuse commonjs modules in the browser and server using modulr?

开发者 https://www.devze.com 2023-03-26 13:16 出处:网络
I\'m using modulr for using commonjs modules in the browser. The goal is to be able to reuse some of those modules also in a server environment.

I'm using modulr for using commonjs modules in the browser. The goal is to be able to reuse some of those modules also in a server environment.

These "shared" modules need to do something like this:

var _ = _ || require("underscore");

meaning:

  • if _ exists as a global var (browser environment), use it
  • else load the "underscore" module (server), and use it instead

Now, since modulr does static analysis in all the code, looking for the require calls in order to generate the final js file, it will fail the build.

Is there a way to work around this problem开发者_开发知识库?

(For example, if modulr supported something like --ignore=<module_list> parameter, everything would run fine.)


Apparently there's no way to fix this in modulr, so I had to create a workaround module named Env which looks like this:

// Env.js

var my = {
    modules: undefined,
    require: require
};

exports.override = function(modules) {
    my.modules = modules;
};

exports.require = function(path) {
    if (my.modules && my.modules[path]) {
        return my.modules[path];
    } else {
        // my.require(...) is needed instead of simply require(...)
        // because simply require(...) will cause a modulr parsing failure
        return my.require(path);
    }
}; 

And at the client side, have a specific initializer that does:

// ClientInitializer.js
Env = require('shared/Env');
Env.override({ underscore: _ });

So, the "shared" modules can do:

// SharedModule.js
var _ = require('shared/Env').require('underscore');  

If the "shared" module is running in the server, the normal require function is called. If it is running in the browser, the Env module will answer with the global _ variable.

0

精彩评论

暂无评论...
验证码 换一张
取 消