Search code examples
javascriptnode.jsgulpnode-modules

Require node_modules from a relative path in gulpfile.js


All works fine when I have the node_modules folder in the sameone as the gulpfile.js.

But whenever I place node_modules anywhere outside it, I can't seem to make it work by using relative paths:

var gulp = require('../../node_modules/gulp');
var rename = require('../../node_modules/gulp-rename');

I get the following message:

[20:11:45] Task 'default' is not in your gulpfile
[20:11:45] Please check the documentation for proper gulpfile formatting

But I in fact have a default task and it runs as expected when not using relative paths.

I also tried including them without specifiying the node_modules folder, as I though it should be:

var gulp = require('../../gulp');
var rename = require('../../gulp-rename');

But I get the following error:

module.js:538 throw err; ^

Error: Cannot find module '../../gulp'

What am I doing wrong?


Solution

  • Try calling require without a path, like this:

    var gulp = require('gulp');
    var rename = require('gulp-rename');
    

    This triggers require to search for the node_modules folder, automatically checking each parent folder up to the root. https://nodejs.org/api/modules.html#modules_loading_from_node_modules_folders