NodeJS local modules for complex application structures

大城市里の小女人 提交于 2019-11-30 23:30:29

You can put your "my/app/components/product/grid/item" files into node_modules/grid/item.js and then when you require('grid/item') in your application code you will get the file you want with a much terser require path syntax. Just check node_modules/grid/item.js and whichever other files into git. The node_modules/ directory need not even be at the top-level since the require algorithm used by node and browserify will search for node_modules/ directories from the current path all the way down to / until it finds a matching module.

Just make sure to add "grid" to the "bundledDependencies" array in your package.json so you don't accidentally install something over it.

You can read more about checking node modules into git.

Read the section of the browserify handbook about avoiding ../../../../../../ for more information.

NODE_PATH is always a bad idea and browserify doesn't support it. Don't ever use it ever.

One thing you could possibly do is create an alias for your helpers in your require config...

require.config({
    paths: {
        "helpers": "my/app/lib/helpers"    
    }
});

That would cut down on some of your long paths.

The problem of the require() function is that the paths are relative from the current file. You could put your modules inside the node_modules directory but this is the worst thing you could do. node_modules is the directory where live all the third-party modules. If you follow this simple rule it's very easy and handy to stay always up to date, you can remove all the dependencies (removing the node_modules) and just doing npm install.

The best solution is to define your own require function and make it global. For example:

Your project structure is:

my-project
| tools
|- docs
|- logs
|- conf
`- src
   |- node_modules
   |- package.json
   |- mod.js
   |- a
   |  `- b
   |     `- c.js
   `- d
      `- app.js

mod.js

global.mod = function (file){
  return require ("./" + file);
};

app.js

//This should be the first line in your main script
require ("../mod");

//Now all the modules are relative from the `src` directory
//You want to use the a/b/c.js module
var c = mod ("a/b/c");

That's all, easy. If you want to get a third-party module located in node_modules use require(). If you want to get your own modules use mod().

And remember, node_modules is only for third-party modules, rule nº1.

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