Reputation: 1975
I can't get export default { multiple, functions } to work.
Heres my setup:
src/index.js
:
import {foo} from './foo'
foo();
foo.js
:
const foo = () => {
console.log("Hello!");
}
export default {foo};
and my package.json
:
{
"name": "jestjs.io",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node src/index.js",
"test": "jest"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.4.5",
"@babel/node": "^7.4.5",
"@babel/preset-env": "^7.4.5",
"babel-jest": "^24.8.0",
"jest": "^24.8.0",
"nodemon": "^1.19.1"
}
}
when I run npm start
, I get the following error message:
/src/index.js:5
(0, _foo.foo)();
^
TypeError: (0 , _foo.foo) is not a function
However, if I export default foo
and import foo
without the curly braces {foo}
, it executes and I get Hello!
printed to the terminal.
What am I doing wrong ?
Upvotes: 4
Views: 1214
Reputation: 12954
You have used a default export and you try to access it using the named import syntax which is not possible, so you need first to import the default export:
import fooObj from '/.foo'; // {foo: f}
then you can access to your foo
function:
fooObj.foo(); // Hello
Or you can use Object destructuring
if the object contains multiple properties:
import fooObj from '/.foo'; // {foo: f, bar: f}
const { foo, bar } = fooObj;
foo();
bar();
You can also export foo
withtout {}
:
const foo = () => {
console.log("Hello!");
}
export default foo;
Then import it like this:
import foo from './foo';
foo(); // Hello
Or you can use a named export:
export const foo = () => {
console.log("Hello!");
}
then:
import {foo} from './foo';
foo(); // Hello
Upvotes: 3
Reputation: 1975
I finally found the solution I was looking for!
// foobar.js
const foo = () => {
console.log("Hello FOO!");
}
const bar = () => {
console.log("Hello BAR!");
}
export default {foo, bar}
//
index.js
import foobar from "./foobar"
const {foo, bar} = foobar
foo();
bar();
Thanks for all your help ! The other answers and comments made it clear to me what I was doing wrong.
Upvotes: 0
Reputation: 42
Try exporting it like this:
const foo = () => {
console.log("Hello!");
}
export default foo;
This would make foo
the default export from this file. If you want to export multiple files, you can do this.
export const foo = () => {
console.log("Hello!");
}
export const bar = () => {
console.log("Hello!");
}
the difference is when importing, you can import the first one (default export) with any name, while the second has to be the exact name with which you exported it.
e.g import {foo, bar} from 'path/path'
Upvotes: 1