Import and export in more detail
Time Box
Activity | Time |
---|---|
Reading | 0.5 hours |
When we used the import
keyword in the previous exercise, it looked like this:
import { encode } from './encode.js'
The last component is the URL of the module we want to import. It's important to remember that this is not a file path, so things like this will not work out:
import { encode } from 'c:\\Users\\gerard\\My Documents\\encode.js'
The other part of an import specifies what you want to import from the other module.
There are four forms of import declarations, we're only going to look at a couple here Named Exports and Default Exports
For more details see the MDN page
Named exports
Named exports are used when a module exports multiple values so they each need a separate name.
The two main ways of writing a named export are like this:
const apple = 'Crispy red sphere'const banana = 'Squishy yellow cresent'function peel(fruit) {return 'beige lumps'}// Export the values named apple and bananaexport { apple, banana, peel }
or more commonly in our codebase, we use this style:
export const apple = 'Crispy red sphere'export const banana = 'Squishy yellow cresent'export function peel(fruit) {return 'beige lumps'}
Importing a named export looks like object destructuring, but is not quite the same:
import { apple, banana } from './fruits.js'console.log(`We have one ${apple} and one ${banana}`)
We can also import the module as a namespace. This can help to avoid conflicts between identical names from different modules
import * as Fruits from './fruits.js'import * as Stocks from './stocks.js'console.log(`I had a delicious ${Fruits.apple} for breakfast`)console.log(`I put all my money into ${Stocks.apple}, so I hope this new iPhone is selling well`)
Again, MDN has all the detail you could want
Default exports
If a module exposes one thing, or one main thing and some other less important things. You might use a "default" export.
// hype-the-crowd.jsexport default function hypeTheCrowd(call, response) {console.log(`When I say ${call}, you say ${response}!`)console.log(`ME: ${call.toUpperCase()}!`)console.log(`CROWD: ${response.toUpperCase()}!`)console.log(`ME: ${call.toUpperCase()}!`)console.log(`CROWD: ${response.toUpperCase()}!`)console.log(`ME: I can't hear you!`)}
... importing a default doesn't use the curly-braces {}
, so it looks like this:
// main.jsimport hypeTheCrowd from './hype-the-crowd.js'hypeTheCrowd('cheese', 'cake')hypeTheCrowd('hot', 'dog')
When you import a value, you can name it whatever you want really. Usually default exports have a conventional name and it is useful for humans reading your code if you use those names, but JavaScript is a robot and does not care what you name them.
This document should be enough to get you started, but eventually you'll want more detail so I recommend you bookmark the MDN Guide for JavaScript Modules.