1

If i have file structure like this:

  • app
    • models
      • model1.ts
      • model2.ts
      • model3.ts
      • index.ts
    • services
      • serviceGroup1
      • serviceGroup1Service1.ts
      • serviceGroup1Service2.ts
      • index.ts
      • serviceGroup2
      • serviceGroup3
      • index.ts

tsconfig.json:

"compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "mapRoot": "/",
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "outDir": "../dist/",
    "rootDir": ".",
    "sourceMap": true,
    "target": "es5",
    "inlineSources": true
}

How to make all model public and import them like this: serviceGroup1Service1.ts:

import * as models from 'models';

Updated file tree

Updated files

Added new barells to system.config.ts

'app',
'app/models',
'app/services'

Trying to use in serviceGroup1Service1.ts

import * from 'app/models'

Have an error "Cannot find module 'app/models'

But

import { Component } from '@angular/core'

works well. How to do it for my components?

1
  • Thanks for answers. But still have error "[ts] Cannot find module". Commented Jul 7, 2016 at 21:02

2 Answers 2

1

Add app/models.ts:

export * from './models/model1`
export * from './models/model2`
export * from './models/model3`

and now you can import them with:

import * as models from 'app/models';

If you want to use just models instead of app/models you should add SystemJS map configuration, something like:

System.config.map = { models: 'app/models' }
Sign up to request clarification or add additional context in comments.

Comments

1

Previous answer works, but I've noticed the angular2 pattern seems to be "barrels" where you would have an index.ts in the models dir that does the "export * from xxx" for each file, then you'd "import * from ./models/". Both approaches work, just the pattern I've noticed.

There might be some built-in support for generating them (maybe in angular-cli? It generated them when I used it for creating a component), I've only needed a couple and generated them by hand.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.