180

The export statement below gives a syntax error

export default const hello = () => console.log("say hello")

why ?

I'm only able to export named functions

export function hello() {
  console.log("hello")
}

What is the reason?

11

3 Answers 3

282

Is it possible to export Arrow functions in ES6/7?

Yes. export doesn't care about the value you want to export.

The export statement below gives a syntax error ... why?

You cannot have a default export and give it a name ("default" is already the name of the export).

Either do

export default () => console.log("say hello");

or

const hello = () => console.log("say hello");
export default hello;
Sign up to request clarification or add additional context in comments.

9 Comments

How does the below work then export default hello = () => { console.log("why the downvote")}
x = y is an assignment expression which resolves to the value of y. It's not a variable declaration. You can put x = y anywhere you can put an expression. Note: This will throw in strict mode if x is not defined beforehand.
what about regular exports ? is it possible to do something like: export () => {/*body*/} as getUsers; ? or do I have to first define it and then export it?
@Tomasz: export const getUser = () => {...};
@Burrich: It shouldn't matter how a function was created as long as it can be used in the way it is supposed to be.
|
54

If you don't want a default export, you can simply export a named function with this syntax:

export const yourFunctionName = () => console.log("say hello");

6 Comments

So you replace export function yourFunctionName () { with export const yourFunctionName = () => . The characters length is the same, but there's a high chance to make a typo within this section = () =>. Honestly, to me it feels less readable and more work :)
Arrow functions differ with normal functions in how they asign this value. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
why do we need const here?
@rahulKushwaha const is used to declare the variable, just like let, but in a way that you cannot change it afterwards. It used to be var in older JS. And export makes it available outside the file
so, export can only work with cont variable?
|
2

Try this

export default () => console.log("say hello");

or

export const hello = () => console.log("say hello")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.