2

I like how React can be imported as a default object like import React from 'react' and imported in a destructured way, like import { useEffect } from 'react' or even import * as Whatever from 'react' if you're feeling cheeky. I'm trying to build my own typescript library for npm that can be imported in all 3 of these ways (in addition to the usual require syntax, and I've spent about 15 hours on it so far without being able to get it to work (frustrating).

Right now I'm using rollup to build lib/cjs and lib/esm, to support both CommonJS and Modules. I'm also having typescript-compiler (tsc) build type files and put them inside /lib/types.

But what I'm REALLY stuck on is how to export my files like how React does it. So far I'm using an index.ts "barrel file" at the root of my library, which is something like:

export * from './filename1' export * from './filename2' ...

But this obviously doesn't provide a default export for my library. Is there some sort of index.d.ts module declaration magic I need to do? Any tips / tutorials on building a typescript library would be helpful. I've been able to get both default imports and named imports to work for my library, but not both at the same time.

Paul Fidika
  • 103
  • 2
  • 7

2 Answers2

1

You can import everything first and then use export default to export everything.

import * as filename1 from './filename1';
import * as filename2 from './filename2';

export default {
  ...filename1,
  ...filename2
};

Does this work for you?

Tobias S.
  • 21,159
  • 4
  • 27
  • 45
  • The problem with that is now when a user imports the library, they'll have to be like: import something from 'library' and then something.filename1.function() which is kind of weird. You also can no longer do destructured imports, like import { function1, function2 } from library; the user would have to first do the default import, and then destructure that default into the components he needs. – Paul Fidika Apr 28 '22 at 19:31
  • I think I'm going to abandon the idea of a default import for the library. All imports will have to be { functionName }, or if they really want a default object, they can do something like import * as default from 'library' and then reference default.functionName() – Paul Fidika Apr 28 '22 at 19:33
0

This should be a comment, but refer to this answer. You can combine exports and a singular default export in a single file. You'll have to do some work to build the default object the way you want it but the following should work:

import * as filename1 from './filename1';
import * as filename2 from './filename2';

// build defaultObject as desired
const defaultObject = Object.assign({}, filename1, filename2)

export default defaultObject;
export * from './filename1';
export * from './filename2';