ES6 like modules per TypeScript > 1.5 

The way you will be using modules in your Angular projects is by using external modules with ES6 syntax, so let's go through the basics of what that means. As mentioned before in this section, there is one file per module and we can export it by using the export keyword. How you consume dependencies, however, differs syntactically; let's illustrate this by creating an ES6 module service.ts and another module consumer.ts, which is meant to consume the former: 

//service.ts
export class Service {
getData() {}
}

//consumer.ts
import {} from './service';

Two things to notice here is in the consumer.ts file:

  • Importing with curly brackets {}
  • Using the from keyword to find our file

The curly bracket {} gives us the opportunity to pick and choose what construct we actually want to import. Imagine if service.ts was more complicated like this:

//service-v2.ts
export class Service {
getData(){}
}

export const PI = 3.14

As a consumer, we could now choose to import Service and/or PI like so:

//consumer-v2.ts
import { Service, PI } from './service-v2'

It is however possible to use an alternate syntax to export your constructs. So far, we have been typing export for each thing we wanted to export; we could type it like this instead in the third installment of our service.ts called service-v3.ts:

//service-v3.ts
class Service {}

const PI = 3.14;

export { Service, PI }

The third way of doing exports is default export. There is such a thing as a default keyword, which means we don't have to use the curly braces {} when importing it:

//service-v4.ts
export default function(a, b) {
return a + b;
}

//consumer-v3.ts
import service from './service-v4';

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset