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')
Thanks for any help!
Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.
Refactoring. Default exports make large-scale refactoring impossible since each importing site can name default import differently (including typos). On the contrary, named exports make such refactoring trivial.
You can have multiple named exports per module but only one default export.
This is the reason the error occurs. To solve the error "The requested module does not provide an export named 'default'", use the default keyword when exporting a value from a file and don't wrap the corresponding import in curly braces. You can only have a single default export per file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With