tys
tys

Reputation: 699

Export as default multiple imported modules

How do I export as default multiple imported modules?

I could do something like the code below, but if I were to import multiple files the boilerplate could grow quickly. Is there a shorthand way to achieve this?

import Foo from './Foo'
import Bar from './Bar'
//...

export default {
    Foo,
    Bar
    //...
}

Note that in my code above, I'm not exporting multiple values. I'm importing multiple values, accumulating them, and exporting them as a single object. I intend to refer to the reexported values by Baz.Foo or Baz.Bar, assuming the code above is Baz.js.

Upvotes: 5

Views: 2271

Answers (4)

dandeto
dandeto

Reputation: 846

Instead of accumulating boilerplate from importing lots of files to simply re-export them, you can do this:

// In library.js
export { default as Foo } from "./Foo.js";
export { default as Bar } from "./Bar.js";

// In new_file.js
import { Foo, Bar } from "../lib/library.js"
var phooey = new Foo();

This selects whatever you are exporting as default and gives it an alias.

Upvotes: 2

WebDeveloperReact
WebDeveloperReact

Reputation: 46

import * as name from "module-name";

This will be a great fit for your application. And when you want to access the object, you can use

name.object = ...;

And let me know, if it is right.

Upvotes: 0

ajaykumar mp
ajaykumar mp

Reputation: 546

In es6 there are two types of exports named and default exports.

Since you want to export default assign all the modules to an object like below

Const modules = {Foo,  Bar }
export default modules;

Then in other files use like below

Import modules from 'path/yourfiles'
modules.Foo.xxx
modules.Bar.xxx

Upvotes: 1

0bero
0bero

Reputation: 1062

export default is not meant to be used with multiple exports: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export#Using_the_default_export

If we want to export a single value or to have a fallback value for your module, you could use a default export

You should use named exports like this:

export {
    Foo,
    Bar
    //...
}

Upvotes: 1

Related Questions