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?
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.
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.
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.
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.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With