AngularJs with Webpack part 1

The goal of this article is to show you and explain how to set up the fastest and simplest possible AngularJs application with Webpack. I will start with simplest angularJs application and build from that, adding loaders and plugins to accommodate different dependencies like bootstrap, filetypes like css etc.

Webpack is a static module bundler for modern JavaScript applications. It also comes with webpack-dev-server we can use to run our application without a need to deploy it on a server. It is equipped with watchers so every change we made in the code will automatically reload our web page. When we build our application is bundled, minimized and optimized. For this article, we will try to explain how to use it with AngularJs.

Before we start with the main concepts let’s set decide which technologies we will use and require.

We need NodeJs with NPM to be installed and added to the PATH. So just go to nodejs and download and install nodejs with npm.  I will use Visual Studio Code as IDE( but you can use anything you prefer). AngularJs will be version 1.7.2 and latest Webpack.



Package.json

First, let’s create a package.json file. I will create a new folder in my Documents folder and name it webpackAndAngularJS. Then open the command prompt and locate the newly created folder or open your folder as a new project in Visual Studio Code and use their terminal.
Type:

npm init -y

This will create a package.json file.

{
  "name": "webpackAndAngularJS",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Install Dependencies

We will need to install dependencies. As I mention we will use AngularJs so let install it using –save and –save-dev decorators so our package.json is updated:

npm install angular --save

After that, we will install other dependencies. So let’s install webapck. We won’t use it only for a build but also for running our application without deploying it. That’s why we will install webpack dev server and webpack cli. Also, we will need one plugin html-webpack-plugin. Index.html will be used as our starting point and this plugin will generate an HTML5 file containing everything from index.html and add all your webpack bundles in the body using script tags. Last one is rimraf. Webpack use it for build options so let install it.

npm install webpack --save-dev
npm install webpack-dev-server --save-dev
npm install webpack-cli --save-dev
npm install html-webpack-plugin --save-dev
npm install rimraf --save-dev

This will be enough for start. Later we will look at leaders and some more plugins etc.




This is how our package.json looks now:

Webpack core concepts

There are four core concepts for webpack.:

  1. Entry
  2. Output
  3. Loaders
  4. Plugins

The entry property, as its name suggests, presents an entry point for your application. It will indicate to Webpack which module should use to begin building out its internal dependency graph.

We are going to use  :

config.entry = {
           app:'./src/app/app.js'
};

 

Output property tells webpack where to emit the bundles it creates and how to name these files. It requires path and file name so we will provide just that.

config.output =  {
    filename: 'my-first-webpack.bundle.js',
    path: path.resolve(__dirname, 'dist')
    };

 

Plugins are used to perform a wider range of tasks like bundle optimization, assets management and injection of environment variables. For now, we will use plugins only in production mode to minimize our JavaScript and check for errors.

  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]

Html Webpack Plugin will take our index.html file and use it as a template to generate a new HTML5 file and add script tags at the end of the body. Script tags will use my-first-webpack.bundle.js output file as src. This is how we connect js files with index.html.
To make it simple we will leave Loaders for later.

Let us create new file webpack.config.js using webapck core concepts.

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');

module.exports = {
  entry: './src/app/app.js',
  output: {
    filename: 'my-first-webpack.bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
   
  },
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

As you can see webpack.config.js has one JavaScript object called module.exports. That object has properties entry, output, plugins we mentioned before and a module which is used for loaders. Configuration is simple. Just set entry point and use html webapck plugin to connect index.html with your build. The build will be added as a script at the end of HTML file. If we want to build the application and deploy it on a server, that build will be in the dist directory and the file will be named my-first-webpack.bundle.js.



AngularJs

After creating webpack configuration we will need some AngularJs to run it and test it. As we set up our application entry point to be ./src/app/app.js from the webapck.config.js file, let us create those two folders and inside the app.js file.

app.js


import angular from 'angular';
var mainApp = angular.module('mainApp', []);
mainApp.controller('appController',  ['$scope', function ($scope) {
    $scope.title ='Hello Angular';
}]
)

Create the mainApp module. Add appController controller. Inside appController create title string variable ‘Hello Angular’ and attach it to the scope so it is available in the view.

Our index.html is in src folder so we will exit app folder and in src create index.html

To connect HTML file with AngularJs add ng-app to HTML tag. This will bootstrap angularJs with the mainApp module. For test purposes add ng-controller=”appController” to body tag. This will make the appController controller for everything inside body tags. To test if everything works we add {{title}} inside h1 tags. This will display title variable that is attached to the appController scope. Angular handles everything inside double brackets. That includes expressions. If you type {{1+1}} in the code it will be displayed 2 on a web page in the browser.

This is now our file structure:





Run it

Before we can run it and test we need to do one more thing. Update our package.json so we can use npm commands to run the server. Inside the scripts part e only had test. Now we will build to create build, server to run a webpack dev server and start so we can run it just by typing npm start.

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "rimraf dist && webpack --bail --progress --profile",
    "server": "webpack-dev-server --history-api-fallback --inline --progress --open --watch",
    "start": "npm run server"
  },

So our final package.json will look:

You can notice that under main is index.js. That is not important because we set our entry point in webpack.config.js. You can delete this line from package.json.

Now we can start the application by typing:  npm start

 

Our AngularJs application started. It is served on webpack dev server on port 8080. We can change that in config also, but this is the default value. As you can see the title is displayed by the angular controller.

If you look at Chrome developer tools inside Elements is our new HTML file. It is same as our index.html template but you will notice that script at the end of the body where our compiled application named my-first-webpack-bundle.js is linked.

In the second part we will look at more complex angularJs application and start to add loaders and plugins. Check it here AngularJs with Webpack part 2: Angular Component and Webpack Loader

vucakivan Author

Leave a Reply

Your email address will not be published. Required fields are marked *