JavaScript Development Tools - Learning JavaScript (2016)

Learning JavaScript (2016)

Chapter 2. JavaScript Development Tools

While you can write JavaScript with nothing more than an editor and a browser (as we saw in the previous chapter), JavaScript developers rely on some useful development tools. Furthermore, because we are focusing on ES6 for the rest of this book, we’ll need a way to convert our ES6 code to portable ES5 code. The tools discussed in this chapter are very common, and you are likely to encounter them in any open source project or software development team. They are:

§ Git, a version control tool that helps you manage your project as it grows, and collaborate with other developers.

§ Node, which allows you to run JavaScript outside of the browser (and comes with npm, which gives you access to the rest of the tools on this list).

§ Gulp, a build tool that automates common development tasks (Grunt is a popular alternative).

§ Babel, a transcompiler that converts ES6 code to portable ES5 code.

§ ESLint, a linter that helps you avoid common mistakes and makes you a better programmer!

Don’t think of this chapter as a distraction from the topic at hand (JavaScript). Think of it as a practical introduction to some important tools and techniques that are commonly used in JavaScript development.

Writing ES6 Today

I have good news and bad news. The good news is that ES6 (aka Harmony, aka JavaScript 2015) is an exciting, delightful evolution in the history of JavaScript. The bad news is that the world isn’t quite ready for it. That doesn’t mean you can’t use it now, but it is going to put an extra burden on the programmer, as ES6 code has to be transcompiled into “safe” ES5 to ensure that it can run anywhere.

Programmers who have been around a while might be thinking “big deal; back in my day, there was no such thing as a language that didn’t have to be compiled and linked!” I’ve been writing software long enough to remember that time, but I do not miss it: I enjoy the lack of fuss in interpreted languages like JavaScript.1

One of the advantages of JavaScript has always been its ubiquity: it became the standard browser scripting language almost overnight, and with the advent of Node, its use broadened beyond the browser. So it is a bit painful to recognize that it will probably be a few years before you can ship ES6 code without worrying about browsers that don’t support it. If you’re a Node developer, the situation is a little bit brighter: because you only have one JavaScript engine to worry about, you can track the progress of ES6 support in Node.

NOTE

The ES6 examples in this book can be run in Firefox, or on a website such as ES6 Fiddle. For “real-world code,” however, you will want to know the tools and techniques in this chapter.

One interesting aspect about JavaScript’s transition from ES5 to ES6 is that, unlike language releases of the past, the adoption is gradual. That is, the browser you’re using right now probably has some—but not all—features available in ES6. This gradual transition is made possible in part by the dynamic nature of JavaScript, and in part by the changing nature of browser updates. You may have heard the term evergreen used to describe browsers: browser manufacturers are moving away from the concept of having discrete browser versions that have to be updated. Browsers, they reason, should be able to keep themselves up to date because they are always connected to the Internet (at least if they are going to be useful). Browsers still have versions, but it is now more reasonable to assume that your users have the latest version—because evergreen browsers don’t give users the option not to upgrade.

Even with evergreen browsers, however, it will be a while before you can rely on all of the great features of ES6 being available on the client side. So for the time being, transcompilation (also called transpilation) is a fact of life.

ES6 Features

There are a lot of new features in ES6—so many that even the transcompilers we’ll be talking about don’t currently support all of them. To help control the chaos, New York–based developer kangax maintains an excellent compatibility table of ES6 (and ES7) features. As of August 2015, the most complete implementation (Babel) is only at 72%. While that may sound discouraging, it’s the most important features that have been implemented first, and all of the features discussed in this book are available in Babel.

We have a little bit of prep work to do before we can start transcompiling. We’ll need to make sure we have the necessary tools, and learn how to set up a new project to use them—a process that will become automatic after you do it a few times. In the meantime, you will probably want to refer back to this chapter as you start new projects.

Installing Git

If you don’t have Git installed on your system, you can find downloads and instructions for your operating system on the Git home page.

The Terminal

Throughout this chapter, we’ll be working in the terminal (also known as the command line or command prompt). The terminal is a text-based way of interacting with your computer, and is commonly used by programmers. Though it is certainly possible to be an effective programmer without ever using the terminal, I believe it is an important skill to have: many tutorials and books assume you’re using a terminal, and many tools are designed to be used on the terminal.

The most ubiquitous terminal experience is a shell (terminal interface) called bash, and it is available by default on Linux and OS X machines. While Windows has its own command-line experience, Git (which we will install next) provides a bash command line, which I recommend you use. In this book, we will be using bash.

On Linux and OS X, look in your programs for the Terminal program. On Windows, after you install Git, look for “Git Bash” in your programs.

When you start the terminal, you see a prompt, which is where you will type commands. The default prompt may include the name of your computer or the directory you’re in, and it will normally end with a dollar sign ($). Thus, in the code samples in this chapter, I will use a dollar sign to indicate the prompt. What follows the prompt is what you should type. For example, to get a listing of the files in the current directory, type ls at the prompt:

$ ls

In Unix, and therefore bash, directory names are separated with a forward slash (/). Even in Windows, where directories are normally separated by backslashes (\), Git Bash translates backslashes to forward slashes. Bash also uses the tilde (~) as a shortcut for your home directory (where you should normally be storing your files).

The basics you’ll need are the ability to change the current directory (cd), and make new directories (mkdir). For example, to go to your home directory, type:

$ cd ~

The command pwd (print working directory) tells you what directory you’re currently in:

$ pwd

To create a subdirectory called test, type:

$ mkdir test

To change to this newly created directory, type:

$ cd test

Two periods (..) are a shortcut for “parent directory.” So to go “up” a directory (if you’ve been following along, this will take you back to your home directory), type:

$ cd ..

There’s a lot more to learn about the terminal, but these basic commands are all you need to get through the material in this chapter. If you want to learn more, I recommend the Console Foundations course on Treehouse.

Your Project Root

You’ll want to create a directory for each project. We’ll call this directory the project root. For example, if you’re following along with the examples in this book, you could create an lj directory, which would be your project root. In all the command-line examples in this book, we’ll assume that you’re in the project root. If you try an example and it doesn’t work, the first thing to verify is that you’re in the project root. Any files we create will be relative to the project root. For example, if your project root is /home/joe/work/lj, and we ask you to create a file public/js/test.js, the full path to that file should be /home/joe/work/lj/public/js/test.js.

Version Control: Git

We won’t discuss version control in detail in this book, but if you’re not using it, you should be. If you’re not familiar with Git, I encourage you to use this book as an opportunity to practice.

First, from your project root, initialize a repository:

$ git init

This will create a project repository for you (there’s now a hidden directory called .git in your project root).

Inevitably, there will be some files you never want tracked in version control: build artifacts, temporary files, and the like. These files can be explicitly excluded in a file called .gitignore. Go ahead and create a .gitignore file now with the following contents:

# npm debugging logs

npm-debug.log*

# project dependencies

node_modules

# OSX folder attributes

.DS_Store

# temporary files

*.tmp

*~

If there are any other “junk” files that you know of, you’re welcome to add them here (for example, if you know your editor creates .bak files, you would add *.bak to this list).

A command you’ll be running a lot is git status, which tells you the current status of your repository. Go ahead and run it now. You should see:

$ git status

On branch master

Initial commit

Untracked files:

(use "git add <file>..." to include in what will be committed)

.gitignore

nothing added to commit but untracked files present (use "git add" to track)

The important thing that Git is telling you is that there’s a new file in the directory (.gitignore), but it’s untracked, meaning Git doesn’t recognize it.

The basic unit of work in a Git repository is the commit. Currently, your repository doesn’t have any commits (you’ve just initialized it and created a file, but you haven’t registered any of that work with Git). Git doesn’t make any assumptions about what files you want to track, so you have to explicitly add .gitignore to the repository:

$ git add .gitignore

We still haven’t created a commit; we’ve simply staged the file .gitignore to go in the next commit. If we run git status again, we will see:

$ git status

On branch master

Initial commit

Changes to be committed:

(use "git rm --cached <file>..." to unstage)

new file: .gitignore

Now .gitignore is to be committed. We still haven’t created a commit yet, but when we do, our changes to .gitignore will be in it. We could add more files, but let’s go ahead and create a commit now:

$ git commit -m "Initial commit: added .gitignore."

The string that follows -m is the commit message: a brief description of the work you’ve done in this commit. This allows you to look back at your commits and see the history of your project unfold.

You can think of a commit as a snapshot of your project at a moment in time. We’ve now taken a snapshot of the project (with only the .gitignore file in it), and you could go back to that at any time. If you run git status now, Git will tell you:

On branch master

nothing to commit, working directory clean

Let’s make some additional changes to our project. In our .gitignore file, we’re ignoring any files named npm-debug.log, but let’s say we want to ignore any files with the .log extension (which is standard practice). Edit the .gitignore file and change that line to *.log. Let’s also add a file called README.md, which is a standard file that explains the project in the popular Markdown format:

= Learning JavaScript, 3rd Edition

== Chapter 2: JavaScript Development Tools

In this chapter we're learning about Git and other

development tools.

Now type git status:

$ git status

On branch master

Changes not staged for commit:

(use "git add <file>..." to update what will be committed)

(use "git checkout -- <file>..." to discard changes in working directory)

modified: .gitignore

Untracked files:

(use "git add <file>..." to include in what will be committed)

README.md

We now have two changes: one to a tracked file (.gitignore) and one to a new file (README.md). We could add the changes as we did before:

$ git add .gitignore

$ git add README.md

But this time we’ll use a shortcut to add all changes, then create a commit with all of those changes:

$ git add -A

$ git commit -m "Ignored all .log files and added README.md."

This is a common pattern you’ll be repeating frequently (adding changes and then committing them). Try to make your commits small and logically consistent: think of them as telling a story to someone else, explaining your thought process. Whenever you make changes to your repository, you’ll be following the same pattern: add one or more changes, then create a commit:

$ git add -A

$ git commit -m "<brief description of the changes you just made>"

TIP

Beginners are often confused by git add; the name makes it seem like you’re adding files to the repository. Those changes can be new files, but just as likely they’re changes to files already in the repository. In other words, you’re adding changes, not files (and a new file is just a special type of change).

This represents the simplest possible Git workflow; if you want to learn more about Git, I recommend GitHub’s Git Tutorial and Jon Loeliger and Matthew McCullough’s book, Version Control with Git, Second Edition.

Package Management: npm

Understanding npm is not strictly necessary to JavaScript development, but it’s increasingly becoming the package management tool of choice. For Node development, it’s practically essential. Whether you’re actually writing Node apps or just doing browser development, you’ll find that life is a lot easier with npm. In particular, we’ll be using npm to install our build tools and transcompilers.

npm comes bundled with Node, so if you haven’t installed Node already, go to the Node.js home page and click on the big green “INSTALL” button. Once you’ve installed Node, verify that npm and Node are functioning on your system. From the command line, do the following:

$ node -v

v4.2.2

$ npm -v

2.14.7

Your version numbers may vary as Node and npm are updated. Broadly speaking, npm manages installed packages. A package can be anything from a full application, to sample code, to a module or library that you’ll use in your project.

npm supports installing packages at two levels: globally and locally. Global packages are usually command-line tools that you’ll use in the development process. Local packages are project-specific. Installing a package is done with the npm install command. Let’s install the popularUnderscore package to see how it works. In your project root, run the following:

$ npm install underscore

underscore@1.8.3 node_modules\underscore

npm is telling you that it installed the latest version of Underscore (1.8.3 as I write this; yours will probably be different). Underscore is a module with no dependencies, so the output from npm is very brief; for some complex modules, you may see pages of text go by! If we wanted to install a specific version of Underscore, we can specify the version number explicitly:

$ npm install underscore@1.8.0

underscore@1.8.0 node_modules\underscore

So where did this module actually get installed? If you look in your directory, you’ll see a new subdirectory called node_modules; any local modules you install will go in this directory. Go ahead and delete the node_modules directory; we’ll be re-creating it in a moment.

As you install modules, you’ll want to keep track of them somehow; the modules you install (and use) are called dependencies of your project. As your project matures, you’ll want a concise way to know what packages your project depends on, and npm does this with a file calledpackage.json. You don’t have to create this file yourself: you can run npm init, and interactively answer some questions (you can simply press Enter for each question and accept the defaults; you can always edit the file and change your answers later). Go ahead and do this now, and take a look at the generated package.json file.

Dependencies are split into regular dependencies and dev dependencies. Dev dependencies are packages that your app can run without, but are helpful or necessary in building your project (we’ll see examples of these soon). From here on out, when you install local packages, you should add either the --save or --saveDev flag; if you don’t, the package will be installed, but not listed in the package.json file. Let’s go ahead and reinstall Underscore with the --save flag:

$ npm install --save underscore

npm WARN package.json lj@1.0.0 No description

npm WARN package.json lj@1.0.0 No repository field.

underscore@1.8.3 node_modules\underscore

You might be wondering what all of these warnings are. npm is telling you that there are some components missing from your package. For the purposes of this book, you can ignore these warnings: you only need to worry about them if you’re using npm to publish your own packages, which is beyond the scope of this book.

Now if you look at your package.json file, you’ll see that Underscore is listed as a dependency. The idea of dependency management is that the dependency versions referenced in package.json are all that’s necessary to re-create (download and install) the dependencies themselves. Let’s try this out. Delete the node_modules directory again, and then run npm install (note we don’t specify any particular package name). npm will install any packages listed in the package.json file. You can look at the newly created node_modules directory to verify this.

Build Tools: Gulp and Grunt

For most development, you’ll probably want a build tool, which automates the repetitive tasks you perform as part of the development process. Currently, the two most popular build tools for JavaScript are Grunt and Gulp. These are both capable build systems. Grunt has been around a couple of years longer than Gulp, so the community is larger, but Gulp is catching up fast. Because Gulp seems to be the increasingly popular choice for new JavaScript programmers, we’ll use it in this book, though I am not prepared to say Gulp is superior to Grunt (or vice versa).

First, you’ll install Gulp globally with:

$ npm install -g gulp

WARNING

If you’re on Linux or OS X, you’ll need elevated privileges to use the -g (global) switch when running npm: sudo install -g gulp. You’ll be prompted for your password and given superuser privileges (for that command only). If you are on a system that someone else manages, you might have to ask them to put you in the sudoers file.

You’ll only need to install Gulp globally once for each system you develop on. Then, for each project, you’ll need a local Gulp, so from your project root, run npm install --save-dev gulp (Gulp is an example of a dev dependency: your app won’t need it to run, but you’ll use it to help with your development process). Now that Gulp has been installed, we create a Gulpfile (gulpfile.js):

const gulp = require('gulp');

// Gulp dependencies go here

gulp.task('default', function() {

// Gulp tasks go here

});

We haven’t actually configured Gulp to do anything yet, but we can verify that Gulp can run successfully now:

$ gulp

[16:16:28] Using gulpfile /home/joe/work/lj/gulpfile.js

[16:16:28] Starting 'default'...

[16:16:28] Finished 'default' after 68 μs

WARNING

If you’re a Windows user, you may get the error “The build tools for Visual Studio 2010 (Platform Toolset = v100) cannot be found.” Many npm packages have a dependency on Visual Studio build tools. You can get a free version of Visual Studio from the product download page. Once you’ve installed Visual Studio, look for “Developer Command Prompt” in your program files. In that command prompt, navigate to your project root and try to install Gulp again, and you should have better luck. You don’t need to continue using the Visual Studio Developer Command Prompt, but it’s the easiest way to install npm modules that have dependencies on Visual Studio.

Project Structure

Before we use Gulp and Babel to convert our ES6 code to ES5, we need to think about where we’re going to put our code within our project. There’s no one universal standard for project layout in JavaScript development: the ecosystem is just too diverse for that. Very commonly, you’ll see source code in src or js directories. We’re going to put our source in es6 directories, to make it perfectly clear that we’re writing ES6 code.

Because many projects include both server-side (Node) code and client-side (browser) code, we’re going to separate these two categories as well. Server-side code will simply go in the es6 directory in our project root, and code destined for the browser will go in public/es6 (by definition, any JavaScript sent to the browser is public, and this is a very common convention).

In the next section, we’ll take our ES6 code and convert it to ES5, so we’ll need a place to put that ES5 code (we don’t want to mix it in with ES6 code). A common convention is to put that code in a directory called dist (for “distribution”).

Putting it all together, your project root will look something like this:

.git # Git

.gitignore

package.json # npm

node_modules

es6 # Node source

dist

public/ # browser source

es6/

dist/

The Transcompilers

As I write this, the two most popular transcompilers are Babel and Traceur. I have used both, and they are both quite capable and easy to use. I am currently leaning slightly toward Babel, and we’ll be using it as the transcompiler in this book. So let’s get started!

Babel started as a ES5 to ES6 transcompiler, and has grown to be a general-purpose transcompiler that’s capable of many different transformations, including ES6, React, and even ES7. Starting with version 6 of Babel, transformations are no longer included with Babel. To perform our ES5 to ES6 transformation, we need to install the ES6 transformations and configure Babel to use them. We make these settings local to our project, as it is conceivable that we’ll want to use ES6 on one project, React on another, and ES7 (or some other variant) on another. First, we install the ES6 (aka ES2015) preset:

$ npm install --save-dev babel-preset-es2015

Then we create a file in our project root called .babelrc (the leading period indicates the file should be normally hidden). The contents of this file are:

{ "presets": ["es2015"] }

With this file in place, any use of Babel in this project recognizes that you’re using ES6.

Running Babel with Gulp

Now we can use Gulp to do something actually useful: convert the ES6 code we’ll be writing to portable ES5 code. We’ll convert any code in es6 and public/es6 to ES5 code in dist and public/dist. We’ll be using a package called gulp-babel, so we start by installing it with npm install --save-dev gulp-babel. Then we edit gulpfile.js:

const gulp = require('gulp');

const babel = require('gulp-babel');

gulp.task('default', function() {

// Node source

gulp.src("es6/**/*.js")

.pipe(babel())

.pipe(gulp.dest("dist"));

// browser source

gulp.src("public/es6/**/*.js")

.pipe(babel())

.pipe(gulp.dest("public/dist"));

});

Gulp uses the concept of a pipeline to do its work. We start off by telling Gulp what files we’re interested in: src("es6/**/*.js"). You might be wondering about the **; that’s a wildcard for “any directory, including subdirectories.” So this source filter will pick up all .js files in es6, and any subdirectories thereof, no matter how deep. Then we pipe those source files to Babel, which is what transforms them from ES6 to ES5. The final step is to pipe the compiled ES5 to its destination, the dist directory. Gulp will preserve the names and directory structure of your source files. For example, the file es6/a.js will be compiled to dist/a.js, and es6/a/b/c.js will be compiled to dist/a/b/c.js. We repeat the same process for the files in our public/es6 directory.

We haven’t learned any ES6 yet, but let’s create an ES6 sample file, and verify that our Gulp configuration is working. Create the file es6/test.js that shows off some of the new features of ES6 (don’t worry if you don’t understand this file; when you’re done with this book, you will!):

'use strict';

// es6 feature: block-scoped "let" declaration

const sentences = [

{ subject: 'JavaScript', verb: 'is', object: 'great' },

{ subject: 'Elephants', verb: 'are', object: 'large' },

];

// es6 feature: object destructuring

function say({ subject, verb, object }) {

// es6 feature: template strings

console.log(`${subject} ${verb} ${object}`);

}

// es6 feature: for..of

for(let s of sentences) {

say(s);

}

Now create a copy of this file in public/es6 (you can change the contents of the sentences array if you want to verify that your files are different). Now type gulp. When it’s done, look in the dist and public/dist directories. You’ll see a test.js file in both places. Go ahead and look at that file, and note that it differs from its ES6 equivalent.

Now let’s try running the ES6 code directly:

$ node es6/test.js

/home/ethan/lje3/es6/test.js:8

function say({ subject, verb, object }) {

^

SyntaxError: Unexpected token {

at exports.runInThisContext (vm.js:53:16)

at Module._compile (module.js:374:25)

at Object.Module._extensions..js (module.js:417:10)

at Module.load (module.js:344:32)

at Function.Module._load (module.js:301:12)

at Function.Module.runMain (module.js:442:10)

at startup (node.js:136:18)

at node.js:966:3

The error you get from Node may be different, as Node is in the process of implementing ES6 features (if you’re reading this book far enough in the future, it may work completely!). Now let’s run the ES5 equivalent:

$ node dist\test.js

JavaScript is great

Elephants are large

We’ve successfully converted ES6 code to portable ES5 code, which should run anywhere! As a last step, add dist and public/dist to your .gitignore file: we want to keep track of the ES6 source, not the ES5 files that are generated from it.

Linting

Do you run a lint roller over your dress or suit before you go to a fancy party or an interview? Of course you do: you want to look your best. Likewise, you can lint your code to make it (and by extension, you) look its best. A linter takes a critical eye to your code and lets you know when you’re making common mistakes. I’ve been writing software for 25 years, and a good linter will still find mistakes in my code before I do. For the beginner, it’s an invaluable tool that can save you a lot of frustration.

There are several JavaScript linters out there, but my preference is Nicholas Zakas’s ESLint. Install ESLint:

npm install -g eslint

Before we start using ESLint, we need to create an .eslintrc configuration file for our project. Each project you work on may have different technologies or standards, and the .eslintrc allows ESLint to lint your code accordingly.

The easiest way to create an .eslintrc file is to run eslint --init, which will interactively ask you some questions and create a default file for you.

In your project root, run eslint --init. The answers you will need to have are:

§ Do you use tabs or space to indent? A recent StackOverflow poll showed that the majority of programmers prefer tabs, but that more experienced programmers prefer spaces. I will let you choose your own path here….

§ Do you prefer single or double quotes for strings? It doesn’t matter what you answer here…we want to be able to use either equally.

§ What line endings do you use (Unix or Windows)? If you’re on Linux or OS X, choose Unix. If you’re on Windows, choose Windows.

§ Do you require semicolons? Yes.

§ Are you using ECMAScript 6 (ES6) features? Yes.

§ Where will your code run (Node or in the browser)? Ideally, you would use a different configuration for browser and Node code, but that’s a more advanced configuration. Go ahead and choose Node.

§ Do you want to use JSX? No. (JSX is a XML-based extension to JavaScript that is used in Facebook’s React UI library. We won’t be using it in this book.)

§ What format do you want your config file to be in (JSON or YAML)? Choose JSON (YAML is a popular data serialization format like JSON, but JSON is more appropriate for JavaScript development).

After you’ve answered all the questions, you will have a .eslintrc file, and we can start using ESLint.

There are several ways to run ESLint. You can run it directly (for example, eslint es6/test.js), integrate into your editor, or add it to your Gulpfile. Editor integration is great, but the instructions differ for every editor and operating system: if you want editor integration, I recommend Googling the name of your editor with “eslint.”

Whether or not you use editor integration, I recommend adding ESLint to your Gulpfile. After all, we have to run Gulp when we want to build, so that’s also a great time to check the quality of our code. First, run:

npm install --save-dev gulp-eslint

Then modify gulpfile.js:

const gulp = require('gulp');

const babel = require('gulp-babel');

const eslint = require('gulp-eslint');

gulp.task('default', function() {

// Run ESLint

gulp.src(["es6/**/*.js", "public/es6/**/*.js"])

.pipe(eslint())

.pipe(eslint.format());

// Node source

gulp.src("es6/**/*.js")

.pipe(babel())

.pipe(gulp.dest("dist"));

// browser source

gulp.src("public/es6/**/*.js")

.pipe(babel())

.pipe(gulp.dest("public/dist"));

});

Now let’s see what ESLint doesn’t like about our code. Because we included ESLint in our default task in the Gulpfile, we can simply run Gulp:

$ gulp

[15:04:16] Using gulpfile ~/git/gulpfile.js

[15:04:16] Starting 'default'...

[15:04:16] Finished 'default' after 84 ms

[15:04:16]

/home/ethan/lj/es6/test.js

4:59 error Unexpected trailing comma comma-dangle

9:5 error Unexpected console statement no-console

✖ 2 problems (2 errors, 0 warnings)

Clearly, Nicholas Zakas and I disagree about trailing commas. Fortunately, ESLint lets you make your own choices about what’s an error and what’s not. The comma-dangle rule defaults to "never", and we have the option of turning it off altogether, or changing it to "always-multiline" (my preference). Let’s edit the .eslintrc file to change this setting (if you agree with Nicholas about trailing commas, you can use the default of "never"). Each rule in the .eslintrc is an array. The first element is a number, where 0 turns the rule off, 1 considers it a warning, and 2 considers it an error:

{

"rules": {

/* changed comma-dangle default...ironically,

we can't use a dangling comma here because

this is a JSON file. */

"comma-dangle": [

2,

"always-multiline"

],

"indent": [

2,

4

],

/* ... */

Now if you run gulp again, you’ll see that our dangling comma no longer causes an error. As a matter of fact, if we remove it, it will cause an error!

The second error refers to using console.log, which is generally considered “sloppy” (even dangerous if you’re targeting legacy browsers) when used in production browser code. For learning purposes, however, you can disable this, as we’ll be using console.log throughout this book. Also, you will probably want to turn off the "quotes" rule. I’ll leave it as a reader’s exercise to disable these rules.

ESLint has a lot of configuration options; they’re all thoroughly documented on the ESLint website.

Now that we can write ES6, transcompile it to portable ES5, and lint our code to improve it, we’re ready to dive into ES6!

Conclusion

In this chapter, we learned that ES6 support is not widespread yet, but it shouldn’t stop you from enjoying the benefits of ES6 today, as you can transcompile your ES6 to portable ES5.

When you’re setting up a new development machine, you’ll want:

§ A good editor (see Chapter 1)

§ Git (visit https://git-scm.com/ for installation instructions)

§ Gulp (npm install -g gulp)

§ ESLint (npm install -g eslint)

When you start a new project (whether it be a scratch project to run the examples in this book, or a real project), you’ll want the following components:

§ A dedicated directory for your project; we call this the project root

§ A Git repository (git init)

§ A package.json file (npm init)

§ A Gulpfile (gulpfile.js; use the one from this chapter)

§ Gulp and Babel local packages (npm install --save-dev gulp gulp-babel babel-preset-es2015)

§ A .babelrc file (contents: { "presets": ["es2015"] })

§ An .eslintrc file (use eslint --init to create it, and edit to your preferences)

§ A subdirectory for Node source (es6)

§ A subdirectory for browser source (public/es6)

Once you have everything set up, your basic workflow will look like this:

1. Make logically consistent, related changes.

2. Run Gulp to test and lint your code.

3. Repeat until your changes work and are lint-free.

4. Check to make sure you’re not about to commit anything you don’t want to (git status). If there are files you don’t want in Git, add them to your .gitignore file.

5. Add all of your changes to Git (git add -A; if you don’t want to add all the changes, use git add for each file instead).

6. Commit your changes (git commit -m "<description of your changes>").

Depending on the project, there may be other steps, such as running tests (usually as a Gulp task), and pushing your code to a shared repository such as GitHub or Bitbucket (git push). However, the steps listed here are a great framework to build on.

Throughout the rest of the book, we’ll present source code without repeating the steps necessary to build and run it. Unless the example is explicitly browser code, all of the code samples should run with Node. So, for example, if you’re given an example example.js, you would put that file ines6, and run it with:

$ gulp

$ node dist/example.js

You can also skip the Gulp step and run it directly with babel-node (though you will not be saving any time, as babel-node also has to transcompile):

$ babel-node es6/example.js

Now it’s time to learn some JavaScript!

1Some JavaScript engines (Node, for example) do compile your JavaScript, but it happens transparently.