5

I'm writing a npm package in Typescript which implements several functions.

At the moment, I'm importing all the functions in a file index.ts and re-export them immediately:

import { functionA, functionB } from "./file1";
import { functionC, functionD } from "./file2";
export {
  function A,
  function B,
  function C,
  function D,  
}

I can use them in other projects using import { functionA } from "package";

However I'd like to export these functions so that I can use the package like this in another project (without using a class):

import _ from "package"
const foo = _.functionA(...);
const bar = _.functionB(...);

This is similar to the implementation of Lodash. I've searched in many places but exporting stuff in typescript is quite confusing (for instance, index.d.ts in lodash has two exports for _ and some declare const, declare namespace stuff...)

2
  • Consider using a namespace import for idiomatic reasons. Commented Feb 24, 2020 at 17:14
  • Consider putting the functions into a class and exporting the class Commented Mar 8, 2022 at 17:25

2 Answers 2

10

Export the default object with those properties:

const _ = {
  functionA,
  functionB
}

export default _;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I'll try this
2

You can import the module in variable using import * as syntax

import * as _ from './package';
_.functionA();

Comments

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.