No matter which IDE, OS or type of computer you use, there are certain tools you will need to know about and understand to successfully set up your local working environment. The most ubiquitous and commonly used of these tools is the Node Package Manager, or npm
.
What is npm
?
Basically, npm
is your JavaScript parts supplier. The Open Source community builds and maintains literally hundreds of thousands of packages for all kinds of JavaScript requirements. These include development packages for processes like:
linting — the process of verifying code quality
transpiling — converting ES6+ JavaScript, TypeScript, etc. into ES5 for maximum browser compatibility
bundling — grouping multiple files into one single file to minimize server requests
minifying — reducing the overall size of files to maximize performance
And that's just for vanilla JavaScript front-end work! You will also use npm
extensively if you go on to learn front-end frameworks or libraries like jQuery, Angular, React, or Vue, and if you learn fullstack development with Node, Express, MongoDB, GraphQL, etc. Anywhere you use JavaScript, you will almost certainly use npm
, so it's certainly worth learning about!
You can also use npm
(and you will in this part of the course) to install global packages on your development machine. These packages can include build tools like Grunt, Gulp, or Webpack for automating and optimizing your build process. In this course, we will be using Gulp.
Installing npm
To install npm on your development machine, you will first need to install Node.js, the JavaScript runtime. You can download and install the latest version from the Node.js website.
Using npm
Let's start with the code from the previous part of this course. Here is index.html
:
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>Chaining requests</title>
</head>
<body>
<div class="container">
<header id="page-header" class="bg-dark text-white col-sm-12">
<h1 id="main-heading" class="text-center">Chaining requests</h1>
</header>
<div class="row">
<section class="col-sm-10 offset-sm-1 text-center">
<button type="button" id="generate-button" class="btn btn-primary btn-lg">Generate Post!</button>
</section>
</div>
<div class="row">
<article class="col-sm-10 offset-sm-1">
<h2 id="post-title"></h2>
<small id="post-id"></small>
<p id="post-content"></p>
</article>
</div>
</div>
<script src="scripts.js"></script>
</body>
</html>
And scripts.js
:
// Get DOM elements
const generateButton = document.getElementById('generate-button');
const postTitle = document.getElementById('post-title');
const postId = document.getElementById('post-id');
const postContent = document.getElementById('post-content');
/**
* Makes an AJAX request of type 'verb' to 'url' with optional 'data' object
* Returns a Promise which resolves or rejects with server response
*/
function makeRequest(verb, url, data) {
return new Promise((resolve, reject) => {
// create and open AJAX request
let request = new XMLHttpRequest();
request.open(verb, url);
request.onreadystatechange = () => {
// only execute code if request is ready
if (request.readyState === 4) {
// request is successful for codes 200 or 201
if (request.status === 200 || request.status === 201) {
resolve(JSON.parse(request.response));
} else {
reject(JSON.parse(request.response));
}
}
};
// for POST requests, set Content-Type header and send request with 'data` object
// otherwise, simply send request
if (verb === 'POST') {
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(data));
} else {
request.send();
}
});
}
/**
* Sends GET requests for uid, title and content in parallel
* Sends resulting object as POST request
* Handles response from POST request and prints result to DOM
*/
async function createPost() {
// create three request Promises (starts sending requests)
const uidPromise = makeRequest('GET', 'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets/generate-uid');
const titlePromise = makeRequest('GET', 'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets/generate-title');
const contentPromise = makeRequest('GET', 'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets/generate-lorem');
// await responses from three requests and assign to three constants
const [uidResponse, titleResponse, contentResponse] = await Promise.all([uidPromise, titlePromise, contentPromise]);
// concatenate data from GET requests and make POST request
const postPromise = makeRequest(
'POST',
'https://us-central1-open-classrooms-js-for-the-web.cloudfunctions.net/widgets/create-post-with-uid',
{uid: uidResponse.uid, title: titleResponse.title, content: contentResponse.lorem}
);
// assign result to constant and print constant properties to DOM
const post = await postPromise;
postTitle.textContent = post.post.title;
postId.textContent = post.post.id;
postContent.textContent = post.post.content
}
// click listener for Generate Post! button
generateButton.addEventListener('click', () => {
createPost();
});
Create both of these files in a new project directory (this will be your working directory until the end of this part of the course). Open a terminal and navigate to that project directory: we are going to initialize our project by running:
npm init
This command creates a package.json
file which will contain your project's dependencies (both development and production) and some metadata about your project. When you run npm init
, you are given the opportunity to add this metadata; you may do so, or you can also simply hit Enter to add default values.
Now that your package.json
file exists, you can use the npm install
command to install packages to your project.
Installing npm
packages
There are three main methods of installing packages with npm
— which one you use will depend on what the package is for. Here is a brief explanation (you will use all three in this part of the course):
npm install -g <package>
— this command will install a package globally on your machine, and is useful mainly for CLI, or command-line interface toolsnpm install <package> --save
— this command will install a package locally to a project, and will save it as a production dependency, necessary for your code to function in a production environmentnpm install <package> --save-dev
— this command will also install a package locally to a project, but will save it as a development dependency, i.e. one that is no longer required once your project is pushed to production
Installing packages locally to your project creates a node_modules
directory. You will not need to modify any files in this directory, as it is managed by npm
. You may also notice, as we go on, that there are many packages in node_modules
we did not actively install — this is because npm
automatically installs package dependencies, making life far simpler for us.
Summary
In this chapter, we saw what npm
is, and what it does for us. We prepared our project directory and its package.json
file, and had a brief look at some of the different ways in which npm
can install packages for us.
In the next chapter, we will start installing and configuring Babel, the JavaScript compiler, to help maximize our code's browser compatibility.