Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Requiring node modules locally

Tags:

node.js

npm

When working with modules already registered on NPM, the process of including them is easy: run npm install <package> and then add var package = require('<package>')

However, I'm not sure of the way to "set things up" when working on my own module. I'm not ready to publish to NPM but I do want to require the module in the same way as outlined before.

Therefore, I've completed the following steps:

  1. Created a sub-directory inside the node_moduels directory for my module
  2. Added a package.json file (via npm init) inside this new directory
  3. Included a dependencies section in the package.json file

Is this the correct approach to using node modules locally.

Also, when I run npm install the dependencies do not appear to be detected in my module's package.json file - I assume this is an issue with the way I've gone about things?

like image 342
tommyd456 Avatar asked Sep 12 '15 10:09

tommyd456


1 Answers

I would not suggest putting it in the node_modules directory. This folder should be excluded from your source control.

Here's a minimal end to end example.

Put this file wherever you like. I suggest a 'lib' folder within your directory structure

myModule.js

module.exports = function(callback){
    return callback("hello there");
}; 

Then, wherever you want to use it:

app.js

var myModule = require('./lib/myModule');

myModule.sayHello(function(hello) {
    console.log(hello);
});

Now, if you run node app.js your console output will be:

hello there

As your myModule grows, you can refactor this into a separate set of files, create an package.json for it, and publish it to NPM

EDIT

Based on your comment, it looks like this is what you want

Local dependency in package.json

So, based on that, along with our above example, edit your package.json as follows

{
  "dependencies": {
    "myModule": "file:../lib/myModule"
  }
}

Then you can require as:

var myModule = require('myModule');

If / when you publish myModule to npm, you can just change your package.json

ANOTHER EDIT

As another alternative, you can specify git urls in your package.json without publishing to NPM

Use Git dependencies with npm and Node on Heroku

like image 155
Alex Avatar answered Sep 22 '22 18:09

Alex