FirstOfMany FirstOfMany - 4 months ago 15
Javascript Question

What are these 3 Angular2 commands importing?

I am studying Angular2 in ES6 JavaScript using this sample app. Specifically, I am trying to map out the chain of dependencies starting at the root JavaScript file for the entire app, which is boot.js. Can someone please explain what exactly is being imported by the following three lines of

boot.js
:

import { CORE_PROVIDERS } from './app/core';
import { AUTH_PROVIDERS } from './app/auth';
import { POSTS_PROVIDERS } from './app/posts';


When I navigate to the
'./app/core'
,
'./app/auth'
, and
'./app/posts'
directories in the GitHub link above, there are so many nested files in those directories that it is not clear to me what exactly is being passed into the three
..._PROVIDERS
variables by the above three commands. Can someone else please explain this?

The complete code for
boot.js
is:

import './shim';
import 'rxjs/add/operator/map';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { FORM_PROVIDERS, LocationStrategy, HashLocationStrategy } from '@angular/common';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent } from './app/core/components/app/app.component';
import { APP_ROUTES_PROVIDER } from './app/core/app.routes';
import { CORE_PROVIDERS } from './app/core';
import { AUTH_PROVIDERS } from './app/auth';
import { POSTS_PROVIDERS } from './app/posts';

if (ENVIRONMENT === 'production') {
enableProdMode();
}

bootstrap(AppComponent, [
FORM_PROVIDERS,
HTTP_PROVIDERS,

APP_ROUTES_PROVIDER,
AUTH_PROVIDERS,
POSTS_PROVIDERS,
CORE_PROVIDERS,

{ provide: LocationStrategy, useClass: HashLocationStrategy },
{ provide: 'ENVIRONMENT', useValue: ENVIRONMENT }
]);

Answer

When you have a

import { Something } from './one/two';

It will look for the Something identifier that was exported by the index file at the two folder.


In your case, when the file located at /client/boot.js does

import { CORE_PROVIDERS } from './app/core';
import { AUTH_PROVIDERS } from './app/auth';
import { POSTS_PROVIDERS } from './app/posts';

The first one looks for the exported CORE_PROVIDERS identifier from /client/app/core/index.js, which is:

import { LoggedInGuard } from './guards/logged-in.guard';
import { LoggedOutGuard } from './guards/logged-out.guard';

export const CORE_PROVIDERS = [LoggedInGuard, LoggedOutGuard];

As you can see, it merely "re-exports" other providers, that are themselves present at other files.

The first one at /client/app/core/guards/logged-in.guard.js and so on.


By the way, this use of index files is a good practice, also suggested at the Angular2 style guide under Create and Import Barrels.