Export Default – Javascript

export default is used to export a single class, function or primitive.

export default function() { } can be used when the function has no name. There can only be one default export in a file.




Example: message.js

export default function(name) {
  return `Hello {name}`;
}

We’ll see how to import this function in another file.

In app.js

  import msg from 'message';
  msg("Peter") // Hello Peter 

Another Example:

Myfunctions.js

	export function square(x) {
	  return x * x;
	}
	export const pi = Math.PI;

This can be imported and used as

Index.js

  import { square, pi } from 'Myfunctions';
  console.log(square(2)); // 4
  console.log(pi);        // 3.141592653589793

Or

	import * as fx from 'Myfunctions';
	console.log(fx.square(2)); // 4
	console.log(fx.foo);    // 3.141592653589793

That’s it!. Please share your thoughts or suggestions in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *