Basit
Basit

Reputation: 17214

Typescript creating modules

I wanted to create modules for our library, so each time we call, we can use import {Api, Map} from "ourlibrary"

currently I'm using following.

import {Api} from "../../Library/Api";
import {MapPage} from "../map/map";

How I can create my own packages to get following result?

import {Api, Map} from "OurLib"

Upvotes: 3

Views: 838

Answers (2)

David L
David L

Reputation: 33873

Create a top-level ES6 style js file that exports your imports as a single file and name it OurLib.

exports.Api = require('../../Library/Api').Api;
exports.Map = require('.../map/map').Map;

The benefit of this approach is that it doesn't tie you to a single module loader system. Since it is straight-forward ES6 features (require/export), it can be consumed by SystemJS, Webpack, Typescript etc.

As mentioned in the comment below, the reason for .Api and .Map at the end of the require statement is because what you are typically importing from your files are classes. You would use syntax like this in the case of

export class Api {}

and

export class Map {}

in each of the respective files. This way you only assign the classes that you WANT to export rather than the entire required file. It gives you more control over your bundled, exposed module.

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202346

I see two steps to do that:

  • Create an entry in the map block of your SystemJS configuration:

    System.config({
      map: {
        'OurLib': 'path-to-ourlib'
      },
      packages: {
        'OurLib': {
          main: 'index.js',
          defaultExtension: 'js'
        }
      }
    });
    
  • Create a TypeScript file (for example, index.ts) as entry point module that import / export what you want to make available outside your library:

    export {Api} from "../../Library/Api";
    export {MapPage} from "../map/map";
    

Upvotes: 1

Related Questions