Patrick Finnigan
Patrick Finnigan

Reputation: 1937

how do I reexport all imports from a module in typescript?

I'm migrating a JS codebase to TS. In JS we have some index.js files which reexport all imports from a module:

export * as users from './users';

What's the equivalent TS for this?

Upvotes: 12

Views: 12187

Answers (4)

charles-allen
charles-allen

Reputation: 4071

It is possible since TypeScript 3.8

Here's a summary of re-export *:

// Re-export *
export * as default from './example1' // as default-import
export * from './example2' // separately
export * as ex3 from './example3' // as a named-object

// usage:
// import ex1, { example2Const, ex3 } from './reexport'
// import * as all from './reexport'

And a reminder of re-export picked:

// Re-export chosen
export { a, b as newB, c as default } from "./example4"; // pick what to export

// usage:
// import c, { a, newB } from './reexport'
// import * as all from './reexport'

Docs:
· Re-export all
· Re-export as named object

Upvotes: 21

mimo
mimo

Reputation: 6817

Another option, how to re-export all named exports (but not a default export) from One module in Second module is to use export * from './one', please see example:

In one.ts we have

// Will be re-exported in Two.ts
export interface One {
    one: string;
}

// Will be re-exported in Two.ts
export const abc = 'abc';

const magicNumber = 123;

// Will NOT be re-exported in Two.ts
export default magicNumber;

In two.ts we have

import * as fromOne from './one'

export interface Two {
    two: number;
    one: fromOne.One
}

and finally we have index.ts, where we can do

import * as fromTwo from './two'

const mNumber = fromTwo.magicNumber; // this will fail, default export is not available

const objectFromOneAndTwo: fromTwo.Two = {
    two: 456,
    one: {
        one: fromTwo.abc
    }
}

Upvotes: 0

Zhaolin Feng
Zhaolin Feng

Reputation: 536

@Patrick Finnigan's anwser is not totally correct. You will have to use users.XXX to access symbols.

Seem there is no easy way to export all symbols.

Upvotes: 1

Patrick Finnigan
Patrick Finnigan

Reputation: 1937

I haven't found a way to do this as a single line, but a coworker pointed out this approach can work:

import * as users from './users';

export {
  users,
};

Upvotes: 7

Related Questions