Using AngularJS and Webpack to implement a Single Page Application

Well, this article is here to help you implement SPA with AngularJS and Webpack. But I am not going to show you every line of code since that will be too much to say. I will just share some of the main concerns and solutions. You can see the complete boilerplate here directly.

Why SPA?

Comparing to traditional websites, a SPA won’t reload the whole page when user tries to navigate to another “page”, instead, the JavaScript will load data asynchronously and change the content.

That sounds simple, but what is the point?

Benefits

SPA has folloing benefits:

  • SPA saves a lot of network load comparing to traditional websites and feels more like an application than a web page.
  • SPA communicates with server with AJAX most of the time, this leads to a better separation between front end and back end.
  • SPA is easy to mock during test since you can fake all the AJAX.
  • SPA is easy to cache resources and make the most use of local storage.

Downsides

Though SPA provides a lot of good thinks, there are some downsides you should know:

  • SEO is hard to handle cause it’s a dynamic web page. You should take a look at this article if your business cares about SEO.
  • Not as easy as you do with traditional websites if you want to implement front-end analytics. Google Analytics has pointed it out.

What takes you to SPA?

To implement a SPA maybe is not as easy as you thought, there is some key points you should know before you get your hands wet:

  • You need to lazy load your “page” resources when navigating if you want to build a scalable SPA.
  • The server needs to route all the “virtual path” to your SPA page entry. A SPA usually has one single entry like “yourdomain.com/index.html”. Whatever page URL the server receives ( like “yourdomain.com/dashborad” ), it returns the entry and leave the real route work to font end.

Front-End requirement and solutions.

Well, let us begin to dive into front end development. We will go through all the things you need to concern when start a new front end project.

  • Browser Compatibility: Prefer Modern browers but it depends the browser market share of your customers. Let the data help you to decide, this article will target to browsers: Chrome, Firefox, Safari, IE9+.
  • ES6: Babel.
  • Style Preprocessor: SASS.
  • Code Style: Use ESLint as the linting utility. Prefer Airbnb’s JavaScript Style Guide
  • Framework: AngularJS ( the lastest AngularJS doesn’t support IE8 anymore ).
  • Libraris & Utilities: jQuery / lodash.
  • Polyfills: Babel-polyfill and others if in need.
  • CommonJS / Module Bundler / Resource Loader: NPM & Webpack.
  • Image Compression and Assets Encoding ( e.g. encoding image or webfont into base64 string ): Webpack loaders.
  • Development enviroment: Webpack-dev-server.
  • Unit Test: Karma and Mocha.
  • E2E Test ( UI Test ): Protractor and Mocha and Chai-as-promised.
  • Online Debugging: Anyproxy.

Hard parts of AngularJS

To implement SPA with AngularJS is not that easy ( Yes, not easy as with React! ).

The first hard thing is to implement a lazy load route. We can choose UI-Route to implement front end routing, but it does not support dynamically routing and it’s a little tricky to lazy load controller either. But fortunately, we can use resolve to wait certain controller to be loaded, and templateProvider will be executed after resolve is resolved:

And we can even build a route-generater to write those code automatically.

Sounds perfect? Then the most fractured thing comes to us: AngularJS does not allow you to register component ( I mean controller, service, filter and directive ) after the module has finishd bootstrapping, which means, even you successfuly load your page script ( with controller definition inside ) and executed, the injector can not find your controller.

That is sucks, but however, I have angular-delay-register to help you overcome this problem.

Basically, you need to use angular-delay-register to set up your module:

and use new methods to register components, like below:

it’s not perfect, but believe me, this is the best way I can find to work around this problem. You don’t want to wrap every component into a new module like ocLazyLoad does, which basically means your write your components like below:

: (

The last things about AngularJS is the dependence injection when you want to compress your code. You may feel happy to write your code like below:

AngularJS’s dependence injection is realy cool, but compression tools like UglifyJS does not know much about it, which will break the literal strings $scope, $http and $q into some kind of random varibles. And believe me, you do not want to change your code manually like below:

Another disaster, but fortunately, we have ng-annotate, the only things we need to get used to is add some annotation before your DI:

Webpack

Webpack is so powerful. With its various loader, we can get lots of features:

  • CommonJS
  • ES6
  • Sass
  • Image / Font / HTML load

It can also integrate ESLint as a preloader to help lint our code in development or buid for production. In addition, benefits from live reload, the page can just reload itself when certain source files change.

(Webpack also provide a feature called Hot Module Replacement, which is very cool, but AngularJS 1.x does not work well with it, so just forget about it)

We can also benefit from code spliting to split our page entries so that we can load each page code asynchronously.

Begin with directory structure.

Below is the basic directory we need for our SPA

Simple enough. Let us talk about each one of them.

App: where source code lies

Below is what inside app

app.js is our main entry, and every page code goes into pages. Since every body needs a module instance, we create a pages/module.js to export this instance, it also includes our module dependences and set up angular-delay-register:

Let’s take a looks at our page controller:

Notice we use registerController() instead of controller(), this is one of the methods that angular-delay-register brings to us, and we also export our view as HTML string, which will be used in routing.

Finally, route.js includes routing works as I told you in Hard parts of AngularJS, which is like:

The most tricky part about route.js is that you need to make sure you use require.ensure with a literal module name like ./dashboard/index instead of varibles. Webpack will only split code automatically this way.

And also take a look at the function pageHandle, its second parameter pageInfo is the page module asynchronously loaded, you can see how the pageInfo.template is used, that why we export view HTML string in pages/[page-name]/index.hs.

Config

The two most important files in /config are:

webpack.config.js is where all the configuration goes, you should have a look at it in our boilerplate, and route-builder.js generates /app/pages/route.js automatically based on what is inside directory /app/pages.

Considering we the route configuration for each page may vary, you can also customize each page route through /app/pages/[page-name]/route.json, it makes routing work easy and also very flexible.

Test: Unit and E2E test goes here

The directory explains itself:

I will talk more about test in this article.

Build: Production code goes here

Basically files in /build are all generated by Webpack except index.html, which is made by us for development, in production this file should be generated by backend so that I can contain some dynamic data inside.

Development

Local development is based on /build/index.html and webpack-dev-server.

/build/index.html:

Notice we add webpack-dev-server.js to enable live reload ( there’s a entry add to /config/webpack.conf.js too ), and use document.write( '<base href="' + location.pathname + '">' ); to create <base> setting to correct path whatever path this application is serverd on.

To make it easy to start development, add command into package.json:

So when you want to start development, type npm run dev, open http://localhost:8080, you are ready to go.

Don’t forget Unit Test

Angular use Karma to do Unit Test. You need to install karma and its browser launcher first ( and I prefer mocha ):

Then you need to set up karma configuration /config/karma.conf.js:

Let us focus on configuration field files. Since all the karma test is goint to run in browser so we need to include all the dependences and code, As we ara using webpack to compile our code with various loders, we can not just include the source files directly, so insteat of using local file path, we use local dev server URL like “http://localhost:8080/vendor.js”.

Also, as we are using Webpack’s code spliting, all the page controllers will not be loaded unless we trigger the routing, but that is not what we want to do since we are not doing UI test.

So the simplest solution to work around this is to create another applicaion entry for unit test named test-launcher.js, which basically just import all the page controllers directly:

Now it’s time to see test spec file /test/unit/test-spec.js:

Also E2E Test

E2E test in much easier, since we do not need to care about how code is organized. As UI Test, you only cares about the if the page runs as you expect.

Let’s install protractor first:

And set up it’s configuration /test/protractor.conf.js:

Since protractor relies on Selenium and Webdriver, you need to install them also:

And we can write our spec now, /test/e2e/route-spec.js:

We test our dev server page directly, so make sure you start your dev server before your run you e2e test.

Leave a Comment

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