Learning React: The Environment – NPM scripts

I’m excited to be learning a second front-end framework, React, because I like the idea of writing ES6 JavaScript components with embedded HTML instead of embedding HTML in JavaScript, like with Angular 1.

A prerequisite to learning React is having a basic understanding of its environment, which includes npm, the package manager for JavaScript. npm allows you to easily install and update modules like jQuery.

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!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s