ES6 how to export all item from one file

7.4k views Asked by At

I want to export all methods of a file from another file.

currently I am doing this, and it works. How can I merge below two into 1 export expression

import  * as db  from './web/query';
export default db;

I tried below written 1 line exports but all failed

export *   from './web/query';  //==error
export *  as default  from './web/query';  //==error
export *  as {default}  from './web/query';  //==error
export from from './web/query'; //== error
export default from './web/query'; //== error

Error means

import db from '../db/index';

db is undefined here. However the the first methods works

Inside of file './web/query' looks like

export function foo(){}
export function baar(){}
4

There are 4 answers

0
Bergi On BEST ANSWER

You cannot in ES2016. To create a module namespace object, you need to give it an identifier (like db) in your current module scope, and then re-export that. There's no way around it.

There is however a stage 1 proposal to add the export * as default from … syntax you were trying.

0
zerkms On

How can I merge below two into 1 export expression

You cannot.

ES2015 (and ES2016) does not provide a syntax that would allow you to import all the named exports from a file and export the object (with those as its properties) as default in a single statement.

0
TeChn4K On

You can export the named exports of another file with export * from '<FILE>';.

// a.js
export const one = '1';
export const two = '2';
// b.js
export * from './a.js';

// c.js
import { one, two } from './b.js';

0
MarcL On

you can do something like this:

a.js:

const fakeName = "Blabla";
const fakeAge = 33;

module.exports = {fakeName, fakeAge}

b.js:

 const name = "Someone";
 let age = 22;

module.exports = { name, age}

c.mjs:

export  * from './a.js';
export * from './b.js';

index.mjs:

import * as  AllClass from './c.mjs'
export default AllClass 

use it in e.g server.mjs:

import AllClass from './index.mjs'

console.log("fakeName:", AllClass.fakeName);
console.log("NAME:",AllClass.name);

It's just hard not to get confused with ESModule imports/exports and CommonJS imports and exports...