Importing/exporting modules

Let's say you're coding a module file and now you're ready to import it into your main file. How will you export it using the official module system? Here's how:

// module.jsconst takeSquareAndAdd2 = num => {    return num*num + 2;}export { takeSquareAndAdd2 }; // #1export const someVariable = 100; // #2export function yourName(name) {    return `Your name ${name} is a nice name` }; // #3export default "Holy moly this is interesting!" // #4
  • #1: We've first coded a function and then, using the export keyword, made it available to other modules that import this particular module.
  • #2: You can directly declare, initialize, and export variables/functions in a single line.
  • #3: As #2 says, you can directly export the functions ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.