How do I import 400+ modules, and iterate over them in my angular-cli project?


I am about to have 400+ models for use with js-data in my angular2 (angular-cli) app.

my project's structure is this:

- src/
  - app/
    - services/
    - pipes/
    - ui/
    - data/
      - store.ts
      - models/
        - model1.ts
        - model2.ts
        - ...
        - model400.ts

In the store, I need to import, and add the mapping to the store. The model files are actually just mapper configs for js-data 3.

currently, they look something like this:

// src/app/data/models/model1.ts
export default {
  schema: {
    name: 'model1',
    properties: { 
      id: { type: 'integer' }
  relations: {}

and my store currently looks like this:

// src/app/data/store.ts
import {
} from 'js-data'
import {HttpAdapter} from 'js-data-http'

declare var require: any

export const adapter = new HttpAdapter({
  // Our API sits behind the /api path
  basePath: '/api'

export const store = new DataStore({});
store.registerAdapter('http', adapter, { default: true });

import { model1Config} from './models/model1';
import { model2Config } from './models/model2';
import { model3Config } from './models/model3';
// at this point, I give up, cause this is more tedious 
// than cutting grass with a finger nail clipper
store.defineMapper('model1', model1Config);
store.defineMapper('model2', model2Config);
store.defineMapper('model3', model3Config);

If there is anyway to iterate over every file in the models folder, that would be great.

angular-cli is supposed to eventually compile all the ts/js to a single js file, so I don't need to worry about anything that couldn't run on the client side. (so, I have broccoli, and whatever other build tools are bundled with that, I just don't know if any of them would be useful to me for this situation)


You could use an index file, which you can use for your imports. for example in your models folder an index file which just exports every model for you like this:

// ...../models/index.ts

export * from './models/model1';
export * from './models/model2';

then in your other files you can import them like this:

import {model1Config, model2Config, model3Config } from "path/to/models/index";

You have to define the exports somewhere. Using a file which functions as a "export collection" saves you at least a lot lines of code (and a lot of time if you're using a good IDE). Setting up the the index with your x-hundreds of models still is tedious. Maybe a little script with gulp could help.

By : lexith

This video can help you solving your question :)
By: admin