In this blog post I’m going to detail the steps to getting started with Angular 2, Babel 6 and Webpack. For the purpose of this blog post, I’ll be using ES7/ES2016 (as opposed to TypeScript). You should be able to add this setup to an existing project (IE: ASP.NET). I used Angular 2 version 2.0.0-beta7 in this example.
Setting up the environment
First, install node.js. I’ve been sticking with the LTS version (Long Term Support) 4.x branch. Once node.js is installed, open a terminal and install webpack globally.
npm install -g webpack
Next, navigate to the root of where your web project exists and run the following commands (the second command is quite long):
npm init
npm install --save-dev webpack angular2 babel-plugin-transform-decorators-legacy babel-loader babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-runtime babel-plugin-transform-runtime babel-core es6-promise@^3.0.2 es6-shim@^0.33.3 reflect-metadata@0.1.2 rxjs@^5.0.0-beta.2 zone.js@0.5.15
Configuring Webpack and Scaffolding the App
We’re going to get a basic configuration for webpack that will get us up and running. This is not an in-depth webpack tutorial, so things like optimizations to your build pipeline wont be covered in this article. In short, we’ll tell webpack the entry point / root of our application code in a folder /src/my-app. Create these two folders and a file underneath called “app.js”. Here’s some sample code to populate app.js to get you started:
We’ll also tell webpack to generate two files, “my-app-bundle.js” under the “my-app” folder, and “angular2.js” under the “src” folder. The angular2.js file is shared between any other applications you might add later, whereas the “my-app-bundle.js” is the bundled up copy of the specific application, sans Angular 2 dependencies.
Next, create a webpack.config.js in the root of your web application:
Referencing the App from Markup
The next thing to do is create the markup needed to bootstrap the Angular 2 application and reference the two script files. The markup will probably look something like this:
Compiling and bundling the app
You’re almost ready to go. The final step is to simply run “webpack” from the command-line in the root folder of your web application. The output should look something like this:
If you got any errors, the first thing to do is double check your dependencies that are installed via npm and your file paths.
Now that the files are generated, you should be able to see your application!
Next steps
There are facilities to watch code built into webpack, and minification and optimization is just a few extra lines of code/dependencies. I’d say the first place to start is the webpack documentation. You can also invoke webpack directly from gulp to make it part of your pipeline.