First Steps with Babel

Now that you have your tools installed and your files in place, it is time to get started with ES6.

For the moment, you will use Babel from the command line. Later, you will add it to your npm scripts so that compilation happens automatically. That way, as you work with new ES6 features you can focus on the new syntax without worrying about running extra commands in the terminal.

Class syntax

The first ES6 feature you will use for building the Chattrbox client is the class keyword. It is important to keep in mind that the ES6 class keyword does not work exactly like classes in other programming languages. Instead, ES6 classes merely provide a shorter syntax for constructor functions and prototype methods.

Open app.js and define a new class called ChatApp.

class ChatApp {
}

In this chapter, ChatApp will not do much. Ultimately, though, ChatApp will be responsible for most of your application logic.

The definition of the class is currently empty. Add a constructor method with a console.log statement:

class ChatApp {
  constructor() {
    console.log('Hello ES6!');
  }
}

constructor is a method that is run any time you create a new instance of a class. Usually, the constructor will set values for properties belonging to the instance.

Next, create an instance of ChatApp in app.js, right after the class declaration:

class ChatApp {
  constructor() {
    console.log('Hello ES6!');
  }
}
new ChatApp();

Let’s give your code a test run. Open a second terminal window and switch to Chattrbox’s root directory, where package.json, index.js, and app/ live. You will use this window to run your build commands and keep the other one open for running your server.

To test your code, use Babel to compile app/scripts/src/app.js and output the result to app/scripts/dist/main.js:

babel app/scripts/src/app.js -o app/scripts/dist/main.js

If you do not see anything happen in your terminal, that is normal – and good news. Babel will not report anything on the command line unless there is an error (Figure 17.8).

Figure 17.8  Babel works quietly

Babel works quietly

Make sure your Node server is running in your other terminal (with npm run dev), and open your browser to http://localhost:3000. Now you will see your results (Figure 17.9).

Figure 17.9  Hello, ES6!

Hello, ES6!

Your app/index.html sources the main.js you generated from app.js. And because app.js creates a new ChatApp, the code in ChatApp’s constructor is run, logging out Hello ES6!

Now that you have confirmed that Babel is working with a single JavaScript file, it is time to start working with multiple modules.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.247.68