Using npm to install Bower locally and install dependencies as a run script - mhulse/mhulse.github.io GitHub Wiki

Use npm to install Bower locally; then use bower (as an npm script) to install dependencies (like normalize.css):

Tested using:

$ npm -v
2.1.2

You can test this workflow by cding to your desktop, mkdir foo && cd foo.

Next, create an npm package.json file:

$ npm init

… and follow the on-screen instructions.

Here’s an example package.json file with the bare minimum keys needed to make this work (technically, name and version are required):

{
  "name": "npm",
  "version": "0.0.0",
  "devDependencies": {},
  "scripts": {}
}

Rather than install Bower globally using npm install bower -g, we’re going to install it locally and then run everything as an npm script.

Install Bower and omit the -g flag:

# Install locally by not using -g (global) flag:
$ npm install bower --save-dev

Follow the on-screen instructions. The --save-dev flag will save the package information to your package.json devDependencies key.

Once installed, you can modify/simplify your package.json to look like so:

{
  "name": "npm",
  "version": "0.0.0",
  "devDependencies": {
    "bower": "~1"
  },
  "scripts": {
    "bower": "bower"
  }
}

Note that I added bower as a script. This means that we can use npm to run Bower as an npm script.

Next, we need to setup a bower.json which will house our Bower dependencies:

# Run bower as an npm script:
npm run bower init

Follow the on-screen instructions.

When all is said and done, this is what your bower.json file should look like:

{
  "name": "bower",
  "devDependencies": {}
}

Next, install a dependency:

npm run bower install normalize-css#~3 -- --save-dev

Using Bower‘s --save-dev flag, this will save the package information to your bower.json devDependencies key:

{
  "name": "bower",
  "devDependencies": {
    "normalize-css": "~3.0.2"
  }
}

Note that when running scripts via npm, if you need to pass flags to said scripts, you need to seperate those flags using --, for example:

# The Bower version:
$ npm run bower -- -v

> [email protected] bower /Volumes/storage/Users/mhulse/Desktop/foo
> bower -v

1.3.12

That’s it!

Update local npm dependencies:

# This updates Bower:
$ npm update

Install local Bower dependencies (via npm):

# Use this if using bower.json for first time:
$ npm run bower install

Belated TL;DR:

If you were to take the complete json files listed above, put them in foo/, then you could run:

$ cd foo
$ npm install
$ npm run bower install

Done!