How should I configure multiple paths for require?
I have the following structure:
application
|-server
| |-main.js
| |-myClass.js
| |-myClass.js
| |-implementationClass.js
|-common
| |-myOtherClass.js
| |-anotherClass.js
| |-yetAnotherClass.js
|-client
| |-aClientClass.js
| |-anotherClientClass.js
| |-implementationClass.js
I want to be able to do something like this:
require('myClass');
require('myOtherClass');
How should I configure the multiple paths?
currently using require.paths gives me an error : Error: require.paths is removed.
I want to keep this structure as my application has to serve static .js files from shared and I want to avoid sharing server-side .js files.
Also the files use a require() function on the client which emulates the node.js require() and I don't want to use relative paths.
the catch is that when I call require('anotherClass') it has to work on the client and on the server. So using relative paths could work but I also have the require('implementationClass') which returns either the client implementation or the server implementation, and when they are called from the common classes this approach will fail.
Best practice to require sub-modules is by using relative paths:
require('./server/myClass');
require('./common/myOtherClass');
If you are using requirejs, you can configure aliases for client-side:
require.config({
baseUrl: "http://example.com/static/",
paths: {
"myClass": "./server/myClass",
"myOtherClass": "./common/myOtherClass"
}
});
I do recommend doing something like the above, but if you really want to be able to require them globally you can set or modify the NODE_PATH environmental variable before launching your app. require.paths was removed since it only caused problems.
global.mod = function (file){
return require (path.resolve ("../..", file));
};
var myClass = mod ("server/myClass");
var myOtherClass = mod ("common/myOtherClass");
Using require with a relative path for your own modules is a very*1/0 ugly and bad approach.