To initialize an npm project, run npm init from the console. This will generate a package.json file in the root folder of your project.
To install a package like jQuery, run npm install jquery –save. This creates a new folder called ‘node_modules’ in your project and downloads the jQuery package to it.
The –save part of the command will include jquery under dependencies in package.json. This is nifty because when a colleague clones your project, they can simply run npm install and any dependencies in package.json will be downloaded to their node_modules folder.
Another cool feature of npm is scripts. Scripts allow you to store commands that would otherwise be cumbersome to type out in the console. For example, instead of always typing karma start –singleRun to run your Karma tests, you can define a script like…
… and now you just have to type npm test to run your specs. This comes in handy as a project grows and files get deeply nested, as you deploy and have to manage ever more command line tasks.
When I first learned about npm scripts, I found it helpful to compare them with Rake tasks in Rails. Although Rake tasks are more substantive and involve functional code snippets, like npm scripts, they allow you to define administrative tasks and run them from the command line by their definition. Here’s a fallback Rake task I wrote to upload files to Amazon S3 that are older than 300 seconds:
To execute this task you would run rake:upload_jobs from Rails console, or use a scheduler to automate it every few hours.
Next I’ll be learning about the module bundler webpack and building my first React component!