3

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"

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

why to use .Api & .map at the end of line ?
You would typically be referencing a specific class within that imported file.
you mean .Api and .map is the name of exported class ?
@Basit The global "namespace" would be defined by the file name "OurFile". And you CAN export all, however, that would prevent you from any renaming/remapping that you would want to do and it would literally export all, which you might not want to do.
@Basit what does your index.d.ts file look like? is anything actually being exported in it?
|
1

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";
    

2 Comments

I'm using ionic, which has tscnofig.json... how can I use settings on tsconfig? pastie.org/10752352 - it also have webdev.. kind of not sure if this goes on webdev or tsconfig
You mean that you want to define a contract for your lib, i.e. a ourlib.d.ts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.