Migrating from AngularJS to Angular Using a “Hybrid” Approach—a Case Study

Getting into a project based on AngularJS in its 1.4 version is not the most exciting thing that can happen to a programmer in 2019. And it doesn’t matter whether you’re a junior front-end developer or a senior engineer—working with AngularJS simply feels like 2014 all over again (an eternity ago in JavaScript years). But learning that the client intended to migrate to the latest version of Angular soon…

Now THIS was something.

Our team was quite excited with the perspective. Working with the most cutting-edge toolset is always an opportunity to grow as professionals and to dive into all the latest hip solutions which is just pure fun.

We do prefer to start projects from scratch and choose the setup that suits our liking and project requirements. But that wasn’t the case this time around. We had to keep building upon the existing AngularJS application for a few months and work on bug fixes at the same time. The reasons were obvious: the application’s end users expected new features as well as performance improvements. How? We decided on incremental refactoring using a “hybrid” approach. And below you’ll find an outline of what exactly went into the process hiding behind the popular buzzword.

Move away from AngularJS

Work with JavaScript masterminds who will help you choose the right framework and deliver the best experience for your users.

A Hybrid Approach Using AngularJS and Angular

First, let’s back up a little.

Our team consists of four front-end developers. To reconcile further development with fixing bugs, we decided that half of the team would work on new features and the other half would migrate the old components to the new framework. At this point, we needed to deal with three critical aspects:

the process had to be incremental and we had to work through component after component, service after service, and so on.

the application couldn’t stay frozen during the migration process as we needed to deliver new features

most importantly, no new features would be developed using legacy code.

Running two frameworks side by side sounded like a solution. The migration could be done collaboratively and spread over time—seemed like a win-win situation!

There are some viable alternatives to AngularJS, but we ultimately chose Angular as the heir apparent. Unanimously. The decision was driven primarily by Angular’s official support of the “ngUpgrade” module and its stellar documentation. The transition was even easier because of TypeScript—it has been doing a great job in the current tech stack up to that point and would work well with modern Angular, too.

The migration process was not all roses though. Below, we’ll share some of the experiences of the process and provide a handful of working solutions that helped us through. Hopefully you’ll find it useful when migrating your own app from AngularJS to Angular.

Initial state: AngularJS 1.4

We started with AngularJS 1.4 with TypeScript and Gulp as a task runner. We also had some Bower dependencies and Typings for type definitions. Both are deprecated, however, and have been for some time.

The task before us consisted of the following steps:

Moving to Webpack

Creating an Angular project structure and adding dependencies

Preparing Webpack configuration for hybrid app

Bootstrapping the hybrid app

Bringing SASS and Pug to the party

Hybrid app(first component downgraded)

UI Router

Step 1: Moving to Webpack

As step one, we decided to find a promising replacement for Gulp. Currently, there are two popular task runners out there—SystemJS and Webpack—and we took both into consideration. After some discussions, our development team ultimately chose to go with Webpack.

The reasons behind our decision included sufficient complexity and flexibility to run AngularJS 1.4 and then smoothly handle new Angular. Webpack not only handles module bundling, but can also pack our application and run a dev server. And it can do that for both Angulars equally well. The team's experience also contributed to the decision. Webpack configuration mostly depends on your application’s specification, but you can find a lot of pre-made configurations on GitHub. Instead of diving into a comprehensive rundown of our complete configuration, we’ll outline its most important parts instead. The opening section our Webpack configuration defines the entry property and includes two files: our AngularJS initialization file and the file that collects all global styles.

entry: [
'./src/app/bootstrap.module.ts',
'./src/app/index.scss'
],

The rules section, which contains a loader for TypeScript and SCSS files, is another important part. Depending on your needs, it also should include HTML and asset loaders.

Step 2: Creating an Angular project structure and adding dependencies

Setting up an Angular project without Angular CLI can be complicated. CLI tools are awesome and starting a new project with CLI takes only one command. Sometimes, however, we have to get our hands dirty and start a project without neat tools. Guess what? For us, creating a hybrid app was one of those times. We had to start the Angular project within an already existing AngularJS environment. Before setting up a new project structure, we added Angular dependencies to our existing project. Here’s a part of package.jsonthat shows all the required dependencies.

With all the dependencies installed, we then moved to create the structure of application. After considering a few possible hybrid application structures, we ultimately decided to put all the files related to the Angular application in one directory to separate them from the AngularJS project. This is what our project structure looked like:

We didn't want to change anything in the app directory, so it contains just the AngularJS application as you can see above. The ng-app folder holds all the files related to the new Angular project.

Separating both frameworks allowed us to keep the project structure clean. Components rewritten to new Angular could be easily removed from the old application, which really helped us keep the project organized.

Having installed all dependencies and created the project structure, the next step was to add a minimal configuration for the Angular application. To bootstrap the Angular project, we had to create two files. One to declare AppModule and the other to import dependencies like polyfills and later the Angular package, and bootstrap the application.

With this done, we could move to the next step which was configuring Webpack to run our newly created app.

Step 3: Preparing Webpack configuration for hybrid app

Having Webpack up and running and the Angular project created, it was time to configure Webpack to build the new project. To accomplish that, we needed two additional loaders: ts-loader (which we already had) and angular2-template-loader. The first one helps loading TypeScript files, the other allows us to load external Angular template files. Both should be installed as a dev dependency npm install --save-dev ts-loader angular2-template-loader. The next step was to add a rule to the webpack.config.jsthat would allow us to load TypeScript files and Angular templates. It should look something like this:

Because our Angular project was located in the ng-app directory, we instructed Webpack to search for Angular .ts files only there and omit the AngularJS folder.

The last thing to change in the Webpack configuration was the entry point. It had to point to the file where the Angular AppModule was bootstrapped. In our case, it was main.ts.

Step 4: Bootstrapping the hybrid app

After setting up all the dependencies and creating the startup files, we were finally ready to start our AngularJS project inside the Angular application. We needed to import the AngularJS app in our main.ts module, so it would be visible to the Angular app (e.g. angular.module('webapp', [ .. ]);`) and instruct Angular to bootstrap this module via ngUpgrade:

Our AngularJS application had angular-deferred-bootstrap set up. This component provides a function which resolves before app start. It can be used to collect data from the backend, the configuration for example. Unfortunately, this third-party library wasn't working with ngUpgrade.

The new Angular provides a similar mechanism called the APP_INITIALIZER token. It allows us to connect to the bootstrap process and perform some action, talking to the backend, for example. The tricky part was to pass that data to AngularJS and utilize it there.

To do so, we created a service that talks to the backend and collects the required configuration. Then this service had to be downgraded to AngularJS. The ngUpgrade module provides an appropriate static method called downgradeInjectable. Sample usage in AngularJS:

Step 5: Bringing SASS and Pug to the party

We use SASS in the old AnuglarJS application and we wanted to use it with the new framework, too. It’s much more powerful than pure CSS and lets us use variables, mathematical operations, mixins, loops, imports, and other interesting features that make writing styles easier and more fun. To do so, we had to use Webpack plugins—raw-loader and naturally sass-loader. Apart from installing those packages, one additional step still needed to be taken. We had to exclude the ng-app directory from the global SASS-loader rule and create a new one just for Angular:

We decided that we didn’t want to write classic HTML for the sake of readability. There are many template engines available out there, but PUG seems to be a proven solution and we already have a track record with it. It has no problems with Angular’s specific attributes and its configuration with Webpack is easy as well.

The next to last thing for us to do was install dependencies:

yarn add -D pug pug-loader apply-loader

And then, in a final touch, we expanded webpack.config.js by adding loaders:

{
test: /.pug$/,
loader: ['apply-loader', 'pug-loader'],
},

Step 6: Hybrid app (first component downgraded)

Once the hybrid app was up and running, we were ready to start the process of upgrading code. One of the most common patterns for doing that is to use an Angular component in an AngularJS context. This could be a completely new component or one that was previously AngularJS but has been rewritten for Angular.

The ngUpgrade module provides an appropriate static method called downgradeInjectable, the same we used earlier during the configService implementation.

import { downgradeComponent } from '@angular/upgrade/static';

Let’s say we had a simple Angular component:

import { MonteNewAngularComponent } from './test.component';

If we wanted to use this component from AngularJS, we would need to downgrade it using the downgradeComponent() method. As a result, we’d get an AngularJS directive, which you can then register in the AngularJS module:

Step 7: UI Router

Downgrading or upgrading components is not the only way to successful migration. We found out that UI Router that was already there could just as well help us with our task. It can switch logic between AngularJS and new Angular thanks to its support for hybrid apps. The angular-hybrid module enables UI Router to route to both AngularJS and Angular components. And that’s exactly what we needed!

We followed the steps described in the UI Router documentation to make adjustments to our hybrid app. In AngularJS, we just added one module in our dependencies:

From this moment onwards, our router was ready to serve both types of components. We decided that this was a much better way rather than upgrading or downgrading components. Then the moment came to create our first route.

It turned out we had to import StateProvider and UrlRouterProvider to a router config file from our upgraded uirouter dependency:

Summary

There you go. If you chose Angular as a successor to your AngularJS app, we hope this article will help you with the transition process. Things to do in this project:

Split large and complex controllers into modern, lightweight components,

Build a modern architecture with separated services layer to properly apply business logic,

Rearrange the project file structure to improve readability and boost development pace.

We’re still in the early stages of our rewriting the app to Angular, and there’s still at at least a few months’ worth of work ahead of us. But we’ve done our homework and writing new components is going smoothly. If you have any questions or comments, we’d be glad to hear from you in the comments section below!