Ionic 3 - import using aliases

In previous article(Making Angular 2+ imports sexier….) we have seen how we can use aliases in order to simplify the code while importing different functionality into our application.

Today, we are going to re-factor our Ionic project import statements from nested structure ‘../../../’ to an alias based ‘@alias’. This helps a lot when you decide to move files around in order to manage your ever evolving project. Let’s do the same magic for Ionic 3 projects as well.

Create a new Ionic project

ionic start improve-ionic-imports blank && cd improve-ionic-imports

Ionic CLI has created initial directory structure and files for us. Open ‘app.component.ts’ and look closely

import { HomePage } from '../pages/home/home';

Now, as the app grows these import urls become nested. After a period you start to loose track of your imports and it becomes a tedious task. Also, in case you want to re-arrange your files, you need to adjust the import paths in a lot of classes.


TS & webpack are here for the rescue. Open tsconfig.json(one at the root of project), and replace it with following code

Following code has been added in the ‘compilerOptions’

"baseUrl": "./src", //This make VS code aware of alias imports
"paths": {
   "@app/*": ["app/*"], // Created aliases for different folders
   "@pages/*": ["pages/*"],
   "@services/*": ["services/*"]

Time to make webpack aware of these changes, so that we can compile our application accordingly. Create a new file named ‘webpack.config.js’ at root of your project

Ionic build scripts provides a lot of hooks to overload the config. Lets update the package.json and provide the path of webpack config to our build scripts

"config": {
"ionic_source_map_type": "source-map",
"ionic_webpack": "./webpack.config.js"

Time to utilize these changes

Find the following code:

import { HomePage } from '../pages/home/home';

Replace it with

import { HomePage } from '@pages/home/home';

That’s it. Now instead of using ‘../../../’ while importing pages in your application, you can use ‘@pages’.

I hope you’ve enjoyed reading, complete source code is available at ‘GitHub’. Happy coding!