Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export a submodule in a Typescript library

So my goal is to create a library in Typescript. My intention is to split up core parts of the library into submodules like RxJS or Angular Material.

RxJS and Angular both support imports like so:

// RxJS
import { map, filter } from 'rxjs/operators';

// Angular
import { MatButtonModule } from '@angular/material/button';

However, I am unable to replicate this myself.

My goal is to do something similar and allow you to import a class with import { foo } from 'package/bar;

I have looked at RxJS's source on Github and have tried replicating what they've done but it's not working.

The library compiles fine but when I go about importing it I always get a Cannot resolve dependency 'package/foo' error. Meanwhile doing import { test } from package (without the submodule part) works completely fine.

I've tried using paths in tsconfig to no avail. If that is the answer then I'm doing it wrong.

How do I go about doing this?

like image 971
Noah Avatar asked Dec 08 '18 08:12

Noah


People also ask

How do I export a TS module?

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.

How do I export functions in TypeScript?

Use named exports to export a function in TypeScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file' . You can use as many named exports as necessary in a single file.

How do I export a TypeScript class?

Use named exports to export multiple classes in TypeScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a file.

What is default export in TypeScript?

It's just JavaScript Modules and their associated keyword like import , export , and export default are JavaScript constructs, not typescript. However typescript added the exporting and importing of interfaces and type aliases to it.


1 Answers

In order to achieve that, you can create your "sub-modules" in different directories (although they are technically part of the same module), and create an index.ts on each of those directories exporting there whatever you want to publish.

For example, I have done this in my NodeJs package Flowed, and you can for example do this:

import { FlowManager } from 'flowed/dist/engine';

Where the corresponding index.ts file is this one if you want to check.

Although in my case I put also available all the stuff from the root, so the previous line would be equivalent to:

import { FlowManager } from 'flowed';
like image 196
Daniel Duarte Avatar answered Oct 06 '22 01:10

Daniel Duarte