Understanding Ionic 2: Imports

posted in: Uncategorized | 7

A very important concept in Ionic 1.0 was the concept of modules. This allowed you to build an app in a very modular way making your code organized, reusable, logical, easy to understand, scalable, and so much more. It also allowed Angular’s dependency injection system to do it’s magic.

In Ionic 2, we get to use the magic of ES6 imports. This is a more straight forward system of marking classes as exportable and a straight forward syntax of importing these clases into other parts of your app.

In this article we’ll take a a quick look at some of the capabilities of the new import system.

Ionic 1.0 Equivalent

As stated above, if you are coming from ionic 1.0, you may be familiar with modules and dependency injection (If you’re not familiar with modules in Ionic 1, you may want to read my post on the topic). The new system in version 2 will be very familiar and comfortable if you have worked in any server side languages.

Basic Import Syntax

The basic syntax of an import is as follows:

import {thing} from 'path/to/thing';

thing is the name of the class you would like to import. 'path/to/thing' is the path to the file which contains the class. In the path to the file, simply putting the name of a JavaScript file assumes you are referring to the current folder. Adding “./” to the beginning of the path denotes that the path is relative to the current folder. “../” denotes to go up a folder.

Examples

For example, lets assume our code is in an app.js file in the /app folder. Our structure looks something like this:

/www
	/app
		/about
			about.js
		/data
			service.js
		app.js
		specialscript.js
	index.html		

Using the above structure, if we wanted to load in specialscript.js to app.js, we would use the name of the file preceded by ./ since it lives in the same folder (/app).

import {specialClass} from './specialscript';

You’ll notice we didn’t include the .js in the path as it is not required.

Next, we want to import about.js into our app.js file. For this, we will need to use a relative path into the about folder.

import {specialClass} from 'specialscript';
import {AboutPage} from './about/about';

Finally, we want to import service.js into about.js. For this, we will need to go up a folder, and into the data folder.

import {dataService} from '../data/service';

Aliases

Lets pretend we have a class with a super, ugly long name and we REALLY don’t want to use that name. Good news! We can alias it and call it something else in our import.

import { HelloThisClassNameIsWayTooLongCauseSomeoneFeltLikeIt AS TerribleClass } from 'badClasses'

alias imports

Multiple Classes

Another thing we can do is have multiple imports from the same file. To do this, we just comma separate the names of the classes in our import.

import {dataService, peopleService, otherService} from '../data/service';

Exports

There is one question remaining. How do I mark a class as importable? Easy! You mark it with the keyword export.

export class MyClass {}

Conclusion

Hopefully now imports are totally clear and straight forward, especially if you are coming from Ionic 1.0 and can see the parallel between the old modules and the new import system. Questions? Feel free to leave them below in the comments!

Special Thanks

Huge thanks to Brandy Carney for reviewing/editing this post!

NOTE: Alpha

Please be aware that Ionic 2 is in alpha and is subject to change at any time. If this post becomes inaccurate at any time, feel free to leave a comment and I’ll do my best to update it as soon as I can.

My name is Andrew McGivery. I currently work full time as an application developer at Manulife Financial in Canada. My current passion is building and leading highly engaged teams where employee happiness, learning, and growth is a priority.

7 Responses

  1. cfjedimaster

    You say that the .js is not required – but will it break if used?

    Also – what is the simplest way for me to try this? Forget Ionic for a moment. I’ve got an index.html file loading app.js and I want to test an import. I assume I need to use a transcompiler and perhaps a Grunt/Gulp script to watch/auto reload?

    • Nope! You CAN include the .js r not include it. Will work either way.

      As for trying this, you guessed right. Since imports aren’t really supported yet, you’ll need at the very minimum to use a transcompler. It probably doesn’t matter which one you use, but Ionic uses webpack.

      Using Grunt/Gulp to watch/reload is definitely recommended if you’re going to build out your own tooling. Nice thing about the Ionic CLI is it all comes bundled up nicely for you. 🙂

      • cfjedimaster

        Any chance you could blog a quick demo? Or describe in comments?

      • cfjedimaster

        You know – this may be it: http://blog.ionic.io/ionic-and-typescript-part-1/

        • cfjedimaster

          Ok, I’m a but off the main topic here, if you want me to switch to email/DM, let me know.

          I got a gulp script that watches/compiles the typescript. Works well as far as I can tell. I then try to run it in my browser and it fails because exports/requires are not supported. I thought TypeScript would compile down to something I could use in a released browser?

          • My guess would be your compile target isn’t set properly. Do you have a tsconfig file? Here’s the one from Ionic with ES5 as the compile target.

            {
              "compilerOptions": {
                "target": "ES5",
                "allowNonTsExtensions": true,
                "module": "commonjs",
                "sourceMap": true,
                "isolatedModules": true,
                "noEmitOnError": false,
                "rootDir": ".",
                "emitDecoratorMetadata": true,
                "experimentalDecorators": true
              },
              "compileOnSave": false
            }
            

            OR if you are using gulp-typescript, make sure you are setting the target option.

      • cfjedimaster

        According to gulp-tsc (https://www.npmjs.com/package/gulp-tsc) it should default to es3. It also says the module option is commonjs. Do I need to include commonjs so extends/requires work?

Leave a Reply