Home » Angularjs » How can I get my Angular 2 app to work with barrel file imports?

How can I get my Angular 2 app to work with barrel file imports?

Posted by: admin January 30, 2018 Leave a comment

Questions:

I’m trying to follow the Angular 2 style guideline 04-10 Create and Import Barrels found here: https://angular.io/docs/ts/latest/guide/style-guide.html

When I run my app, angular now tries to load a file that doesn’t exist: “my-component-name-here.js”.

To illustrate the problem, I’ve modified the Angular 2 sample app to use a barrel file and it throws a 404 error now as well.

I put the heroes component files into their own folder called heroes. I created a new file called heroes/index.ts:

export * from './heroes/heroes.component';

I changed the import statement in app.component.ts to:

import { HeroesComponent } from './heroes';

When the app tries to load it has the following error as seen in the developer console:

Error: Error: XHR error (404 Not Found) loading app/heroes.ts(…)

The plunkr is found here:
http://plnkr.co/edit/YXY0PwuFot1g1s6qTqDt?p=preview

I suspect this has something to do with SystemJS but I don’t know enough about it to fix it. Can anyone help? Thanks in advance!

Answers:

you have to make few changes to make barrel work,

index.ts

   export * from './heroes.component';

systemjs.config.js

Add an entry to map like below,

  'heroes':                     'app/heroes', 

then in packages make an entry like below,

  'heroes': { main: 'index.ts',  defaultExtension: 'ts' },

This will resolve barrel issue, but does not completely resolve all your issue as you have reference to hero-detail as well inside heroes component, so you have to work on those.

Hope this helps!!

Questions:
Answers:

As a far I can see in your plunkr, the HeroesComponent class is located within the app/heroes/heroes.component.ts file. So I would use the following instead:

import { HeroesComponent } from './heroes.component';