mpen
mpen

Reputation: 282825

How to export entire module as the default?

e.g.

// lib.js
export function f1() {}
export function f2() {}
export * as default; // invalid syntax

And then in another file:

// app.js
import lib from './lib.js';
lib.f1();

Is there a way to do this without exporting each function explicitly? e.g.

export default {f1, f2}; // tedious

PS: I am aware that I can import * as lib from './lib.js'.

Upvotes: 0

Views: 198

Answers (3)

glued
glued

Reputation: 2629

heres another option:

lib.js

export default {
   someFunctionOne: () =>  {

   },

   someFunctionTwo: () =>  {

   },


   someFunctionThree: () =>  {

   }
};

app.js

import lib from './lib';

lib.someFunctionOne();

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161447

import * as lib from './lib';
export default lib;

should be enough. So the module imports all of its own exports and then exports itself as its default export.

I'll second Bergi's answer though, this isn't great from an API design standpoint, and will probably be slower. If something is using your module and needs to import from it, it should know what it's importing, or ask for them all on its own, your module shouldn't do it for them.

Upvotes: 2

Bergi
Bergi

Reputation: 664206

I am aware that I can import * as lib from './lib.js'.

And you really should. Don't make your API more confusing than it needs to be.

If you still want to default-export your own module namespace object, you can also do

export * as default from "./lib.js"; // self-reference

Upvotes: 1

Related Questions