Importing specific objects from "export default" results in "undefined" - javascript

I'm learning Webpack and therefore testing out some different methods I've observed.
I've created the following JS file, which was a method for exporting I observed in a NPM package.
// test.js
const Foo = { myVar: "Foo" }
const Bar = { myVar: "Bar"}
export default {
Foo,
Bar
}
And inside my app.js I write the following:
// app.js
import { Foo } from './test'
console.log(Foo);
I was expecting that I would get the Foo object from my exported object in test.js but I just get an undefined in the console. Also, Webpack says:
"export 'Foo' was not found in './test'
So, removing the the curly brackets from the import:
// app.js
import Temp from './test'
console.log(Temp);
This produces an object, containing the Foo and Bar objects.
What is wrong and right here?

Remove the default keyword, that's for specifying what your default export is, not for all your exports. You're currently saying that your entire object of exports is the default.
export {
Foo,
Bar
}
The default is for saying if something wasn't specified, this should be the default, e.g:
export {
Foo as default, // import WhateverIWantToCallIt from './test'
Foo, // import { Foo } from './test'
Bar // import { Bar } from './test'
}
// Or you can export things separately:
export function Bar() {...}
export function Foo() {...}
export default Foo; // Declare what the default is

You actually export an object with two parameters:
module.exports = {Foo, Bar}
If you want to use import {Foo} from './file' syntax you should export your constants separately
export const Foo = { myVar: "Foo" }
export const Bar = { myVar: "Bar"}

I think you are confusing destructering with named imports
//this is not destructing but named imports
import { Foo } from './test'
// this is default export.
export default { Foo, Bar }
in order to use named imports you have to use named exports .
as other comments has already explained you have to use
export without default
// test.js
const Foo = { myVar: "Foo" }
const Bar = { myVar: "Bar"}
export default {
Foo,
Bar
}
// app.js
import { Foo } from './test'
console.log(Foo); // works as expected

Related

Import can't recognize exported name when it is re-exported [duplicate]

This question already has answers here:
Named export vs exporting an object
(2 answers)
Closed 2 years ago.
I have the files main.js, a.js and b.js:
main.js
import { foo } from './a'
console.log(foo)
a.js
import objWithFoo from './b'
const bar = 24
export default { ...objWithFoo, bar }
b.js
const foo = 42
export default { foo }
When I ran main.js using node -r esm main.js it gave me this error:
SyntaxError: The requested module 'file:///app/a.js' does not provide an export named 'foo'
Question:
Why is it loosing the named export?
You aren't using named exports - you are default exporting an object with properties.
import stuff from './a';
const { foo } = stuff;
...
If you wanted to use named exports:
import objWithFoo from './b'
const foo = { objWithFoo }
export { foo } // <- named export
const bar = 24
export default { bar } // <- object with properties

How to import anonymous functions in ES6

In ES6, we can import exported modules like this:
import { Abc } from './file-1'; // here Abc is a named export
import Def from './file-2'; // here Def is the default export
But how can we import anonymous functions? Consider this code:
file-3.js:
export function() {
return 'Hello';
}
export function() {
return 'How are you doing?';
}
How can I import above two functions in another file, given that neither are they default exports nor are they named exports (anonymous functions don't have names!)?
Single anonymous function can be exported as default (default export value can be anything). Multiple anonymous functions cannot be exported from a module - so they cannot be imported, too.
export statement follows strict syntax that supports either named or default exports. This will result in syntax error:
export function() {
return 'Hello';
}
These functions should be named exports:
export const foo = function () {
return 'Hello';
}
export const bar = function () {
return 'How are you doing?';
}
So they can be imported under same names.

Destructuring a default export object

Can I destructure a default export object on import?
Given the following export syntax (export default)
const foo = ...
function bar() { ... }
export default { foo, bar };
is the following import syntax valid JS?
import { foo, bar } from './export-file';
I ask because it DOES work on my system, but I've been told it should NOT work according to the spec.
Can I destructure a default export object on import?
No. You can only destructure an object after importing it into a variable.
Notice that imports/exports have syntax and semantics that are completely different from those of object literals / object patterns. The only common thing is that both use curly braces, and their shorthand representations (with only identifier names and commas) are indistinguishable.
Is the following import syntax valid JS?
import { foo, bar } from './export-file';
Yes. It does import two named exports from the module. It's a shorthand notation for
import { foo as foo, bar as bar } from './export-file';
which means "declare a binding foo and let it reference the variable that was exported under the name foo from export-file, and declare a binding bar and let it reference the variable that was exported under the name bar from export-file".
Given the following export syntax (export default)
export default { foo, bar };
does the above import work with this?
No. What it does is to declare an invisible variable, initialise it with the object { foo: foo, bar: bar }, and export it under the name default.
When this module is imported as export-file, the name default will not be used and the names foo and bar will not be found which leads to a SyntaxError.
To fix this, you either need to import the default-exported object:
import { default as obj } from './export-file';
const {foo: foo, bar: bar} = obj;
// or abbreviated:
import obj from './export-file';
const {foo, bar} = obj;
Or you keep your import syntax and instead use named exports:
export { foo as foo, bar as bar };
// or abbreviated:
export { foo, bar };
// or right in the respective declarations:
export const foo = …;
export function bar() { ... }
Can I destructure a default export object on import?
Yes, with Dynamic Imports
To add to Bergi's answer which addresses static imports, note that in the case of dynamic imports, since the returned module is an object, you can use destructuring assignment to import it:
(async function () {
const { default: { foo, bar } } = await import('./export-file.js');
console.log(foo, bar);
})();
Why this works
import operates much differently in different contexts. When used at the beginning of a module, in the format import ... from ... , it is a static import, which has the limitations discussed in Bergi's answer.
When used inside a program in the format import(...), it is considered a dynamic import. The dynamic import operates very much like a function that resolves to an object (as a combination of named exports and the default export, which is assigned to the default property), and can be destructured as such.
In the case of the questioner's example, await import('./export-file.js') will resolve to:
{
default: {
foo: ...,
bar: function bar() {...}
}
}
From here, you can just use nested destructuring to directly assign foo, and bar:
const { default: { foo, bar } } = await import('./export-file.js');

export default vs module.exports differences

This works:
import {bar} from './foo';
bar();
// foo.js
module.exports = {
bar() {}
}
And this works:
import foo from './foo';
foo.bar();
// foo.js
export default {
bar() {}
}
So why doesn't this work?
import {bar} from './foo';
bar();
// foo.js
export default {
bar() {}
}
It throws TypeError: (0 , _foo.bar) is not a function.
When you have
export default {
bar() {}
}
The actual object exported is of the following form:
exports: {
default: {
bar() {}
}
}
When you do a simple import (e.g., import foo from './foo';) you are actually getting the default object inside the import (i.e., exports.default). This will become apparent when you run babel to compile to ES5.
When you try to import a specific function (e.g., import { bar } from './foo';), as per your case, you are actually trying to get exports.bar instead of exports.default.bar. Hence why the bar function is undefined.
When you have just multiple exports:
export function foo() {};
export function bar() {};
You will end up having this object:
exports: {
foo() {},
bar() {}
}
And thus import { bar } from './foo'; will work. This is the similar case with module.exports you are essentially storing an exports object as above. Hence you can import the bar function.
I hope this is clear enough.
curly bracket imports {} are only for named exports.
for default export you are not expected to use them during import.
if you want still use {} for your 3rd case this should work.
import {default as bar } from './foo';
bar();
// foo.js
export default {
bar() {}
}
Of course is not working, you exported foo default and imported it with curly braces {}. To keep it simple remember this, if you're exporting the default way you need no curly braces, but if you're importing normaly an module, you'll use curly braces {} to acces a specific function in the module ;). You can see examples here

Typescript: Import default from CommonJS module, export additional type from typing file

Legacy lib.js:
function Foo () {...}
Foo.a = function() {...}
module.exports = Foo
Typing lib.d.ts:
declare module "foo" {
type Type = "a"|"b"|"c"
interface Foo {
(a: Type): string
...
}
export = Foo
// how do i export Type??
}
Consumer app.ts:
import Foo = require('foo')
// how do i get Type from lib.d.ts??
how do i get Type from lib.d.ts?
If is not exported you cannot get it.
This is a really old question, but I needed to answer it myself. If in this case "Foo" is the default modules.exports, then you can use export default on Foo in the module declaration:
declare module "foo" {
export type Type = "a"|"b"|"c" // export any custom types you like
export default interface Foo { // default works
(a: Type): string
...
}
}
Then elsewhere you can do:
import Foo, { Type } from 'foo'

Categories

Resources