javascriptecmascript-6

ES6 - is there an elegant way to import all named exports but not the default export?


I am looking for an elegant way to import all named exports without having to import the default as well.

In one file I am exporting many named constants plus a default:

// myModule.js
const myDefault = 'my default' 
export const named1 = 'named1' 
export const named2 = 'named2'
// many more named exports - otherwise this would not be an issue...
export default myDefault 

In another file I would like to have an elegant way to import all named exports only, without having to import the default:

// anotherFile.js
// this is what I would like to do, but syntax is not supported, right?
import { * as namedOnly } from './myModule'

I do not want to:

// anotherFile.js
import myDefault, * as namedOnly from './myModule' 

because I do not need the default in anotherFile.js and my linting tools bug me about the defined but unused myDefault. Nor do I want to:

// anotherFile.js
import {
  named1,
  named2,
  ... // many more
} from './myModule'

because that's too much typing. I also do not want to object.omit the default:

// anotherFile.js
import omit from 'object.omit'
import * as all from './myModule'
const namedOnly = omit(all, 'default')

Solution

  • There is no separation between "named" and "default" exports. The default export is a named export, it just happens to have the name default which is special-cased for ease of use by certain syntax.

    The only way to import all of the exported keys is with

    import * as foo from "foo";
    

    and that will include the named export default if there is one. If you wish to exclude it from your checks, it would be up to you do handle that in your own logic, as you have done with your omit() example.