Shannon Hochkins Shannon Hochkins - 5 months ago 26x
Node.js Question

Can you centralize the node_modules folder?

I have many projects that all follow specific folder structures and conventions.

Rather than duplicating the whole project, I'd like to just have a configuration object for each project and each project links to the global framework.

I already have the config being passed into the index.js for each project, but the moment I remove the node_modules folder from each project it no longer works.



So using the above structure, the ideal approach would be to run:

cd /project-a && gulp

However this obviously returns

Cannot find module 'gulp', please try npm install gulp

So my question is, is there a way to stillhave the gulpfile inside the projects, but the node_modules path is set to the global node_modules folder?


You have two options:

  1. Loading from global modules. For example on Linux/Mac you could set the NODE_PATH variable like this:

    export NODE_PATH="/path/to/gulp-framework/node_modules"

    Not really recommended however since that makes it hard to reason about where your modules are located. You'd also have to set the environment variable on every machine that you want to build your project on (though you could write a shell script wrapper for that).

  2. Make a project-a and project-b subdirectories of gulp-framework.

    Node traverses all parent directories looking for node_modules folders if a module can't be found in the current directory, so your projects can kind of "inherit" modules from the gulp-frameworks folder.

  3. For Windows, updating the NODE_PATH variable from within the gulpfile.js.

    The below updates the global node_path variable, when you initially run gulp, all node-processes have already been instantiated, so we run the _initPaths() method again so that it re-uses the updated node_path variable:

    process.env.NODE_PATH = "..gulp/node_modules";

    Note: The process override HAS to be included before the first require method.

    After this has been done, you can now require the gulp framework inside the custom node_path specified:

    exports.framework = require('../gulp')(require('gulp'), paramsOrOptions);

    inside ../gulp/ we have index.js:

    module.exports = function(gulp, paramsOrOptions) {
       // setup your gulp framework starting here.