Search code examples
typescriptangularsystemjs

bundle modules into one "namespace"


I am new to angular2 and system js.

when i use

import {Component, OnInit} from 'angular2/core';

at the top of my typescript class I know that 'angular2/core' actually refers to a number of different classes.

I want to know how to set this up in my own system.js environment.

for example if I have a folder in my app folder called model which contains a separate class for each "object" in my project:

app/model/user.ts app/model/object1.ts app/model/object2.ts app/model/object3.ts

right now in order to use these classes in other parts of my app I have to import each file separately at the top of my ts class

import {User} from '../../model/user';
import {object1} from '../../model/object1';
import {object2} from '../../model/object2';
import {object3} from '../../model/object3';

How can I change it so that I can import like this:

import {User, object1, object2, object3} from '../../model/';

here is mt current system.js set up:

System.config({
    map: { 'app': './Modules/Shifts/app' },
    packages: {
        //sets the root path of the Angular2 App
        'Modules/Shifts/app': {               
            format: 'register',
            defaultExtension: 'js'
        }
    }        
});
System.import('app/boot')
        .then(null, console.error.bind(console));

How do I set this up?

Thanks in advance


Solution

  • The simple solution would be to create a helper file that re-exports necessary classes.

    What you need to do is to create a file called ../../model.ts with the content:

    export {User} from './model/user'
    export {object1} from './model/object1'
    // ...
    

    Now you can rewrite your imports as

    import {User, object1, object2, object3} from '../../model';
    

    Or you could also use ../../model/index.ts with adjusted paths export {User} from './user'.