Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 978
Basit Avatar asked Aug 07 '26 08:08

Basit


2 Answers

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.

like image 177
David L Avatar answered Aug 08 '26 21:08

David L


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";
    
like image 23
Thierry Templier Avatar answered Aug 08 '26 21:08

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!