Using npm to install or update required packages just like bundler for rubygems


Question

I love Bundler, it's great at dependency management. I love npm, installing node packages is easy! I have a nodejs app and would love to be able to specify my apps dependencies and easily install / update them wherever I deploy my app. This isn't a library I'm releasing, it's a full fledged web-app.

I'm aware of the npm bundle command, but that just seems to simply override the directory where packages are installed.

I'm used to using bundler in this fashion:

# Gemfile
gem "rails", "3.0.3"

Installs rails v3.0.3 and any other required gems on the host machine only if it doesn't already exist

> bundle install

How can I achieve something similar with npm?

1
86
3/12/2014 7:52:29 PM

Accepted Answer

As of npm 1.0 (which is now what you get by default if you follow the steps in the README file), "bundle" is no longer a segregated thing -- it's just "how it works".

So:

  1. Put a package.json file in the root of your project
  2. List your deps in that file

    { "name" : "my-project"
    , "version" : "1.0.0"
    , "dependencies" : { "express" : "1.0.0" } }
    
  3. npm install Since you're calling this with no args, and not in global mode, it'll just install all your deps locally.

  4. require("express") and be happy.
145
4/18/2016 7:00:25 PM

Edit: This only applies to npm versions < 1.0


It was quite difficult to figure this out, but NPM makes this possible.

You need three components

  1. A subdirectory in your repository (i.e. deps/)
  2. A package.json file in the above directory that lists dependencies
  3. An index.js file in the above directory that requires your dependencies

Example

Imagine that express is your only dependency

deps/package.json

note: Increment the version # each time you modify the dependencies

{
  "name": "myapp_dependencies",
  "version": "0.0.1",
  "engines": {
    "node": "0.4.1"
  },
  "dependencies":{
    "express": "2.0.0beta2"
  }
}

deps/index.js

export.modules = {
  express: require('express')
  //add more
}

Now you should be able to install your dependencies using npm. You could even make this part of your deployment process

cd deps
npm install

Then within your app code you can get access to your specific version of express like this:

var express = require('myapp_dependencies').express;

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon