Node.js require() vs RequireJS?

2019-03-14 06:02发布

问题:

Hello with RequireJS I can set a base path like this: base : './app/' so when I am in ./app/foo/bar/ for example and I have a script where I use require('foo'); RequireJS then would search for ./app/foo.js and not in node_module folder or in ./app/foo/bar/foo.js this comes handy when you have a kind of structure where it would be much cleaner for you as a developer to see the dependencies instead of having ../../foo.js. I could have ./app/foo.js and ./app/foo/foo.js and ./app/foo/bar/foo.js it would be much more cleaner to have:

require('foo');
require('foo/foo');
require('foo/bar/foo');

rather than:

require('../../foo');
require('../foo');
require('./foo');

Now you could say why not change the name and not have foo everywhere, let's say that we can't for any reason…

Another lack of feature that I see in node's require method against RequireJS is the ability of setting path mapping, if I have a directory named ./app/super-sized-directory-name/ in RequireJS I could simply do 'big-dir' : 'super-sized-directory-name' and then I could simply use require('./app/big-dir/foo') with Node.js's require method this is not possible as far as I know…

回答1:

--alias, -a    Register an alias with a colon separator: "to:from"
             Example: --alias 'jquery:jquery-browserify'   

You can register aliases with browserify, so that covers your renaming.

As for your rooted absolute paths, that can't really be done. As mentioned modul8 has a namespacing mechanism to solve this.

I would recommend you pong SubStack in #stackvm on freenode and ask him directly.



回答2:

It may or may not help you, but I believe the Dojo Frameworks AMD Loader is API compatible with RequireJS and providing you are using a new microkernel does not pollute the global namespace.

I believe it only has require() and define() in the global namespace now.

Anyway their method of dealing with this is to do something like:

require(["dojo/node!util"], function(util){
    // Module available as util
});

The documentation is at http://dojotoolkit.org/reference-guide/1.8/dojo/node.html



回答3:

Use uRequire which provides a 'bridge' between nodejs require and AMD define modules, without reinventing the wheel (it is build on top of the two standards). It basically converts modules from AMD or commonJS format to the other format or UMD that runs smoothly on both nodejs & the browser.

It is also translating dependency paths with flexible path conventions, so you can have either '../../foo' or 'bar/foo' depending on which makes more sense at the point you are at.

Your AMD or UMD modules are loaded asynchronously on browser (using AMD/requireJs or other AMD loader) and on node the asynchronous require(['dep1', 'dep2'], function(dep1,dep2){...}) is also simulated.