Re-export
Learn to forward a module's values to another with export ... from.
What is re-export?
Re-export forwards a value from one module directly to another. You do it with the export ... from syntax: the value is imported and re-exported in one line.
export { greet } from './hello.js';Here greet is not used in this module; it is only passed through from ./hello.js to anyone who imports this module.
Barrel module
A barrel module is a file that distributes values from many modules through a single entry. It contains several export ... from lines.
export { login } from './user.js';
export { token } from './session.js';So a consumer can import both values from one place with a single import. Large libraries set up their public entry this way.
Exercise Write a barrel module
Write an index.js barrel module. Forward both login and logout from ./user.js with a single export ... from statement.
Show example solution
Inside braces write login and logout, name user.js with from.
Example solution:
export { login, logout } from './user.js';
Test yourself
-
Which syntax forwards a value from another module directly?
- export { x } from './m.js'
- import { x } from './m.js'
- export default x
- const x = require('./m.js')
Show answer
export { x } from './m.js' — Correct! export ... from forwards the value straight from its source.
-
Complete the re-export syntax
export { greet } ____ './hello.js';Show answer
export { greet } from './hello.js'; -
Match the re-export concepts
- export { x } from
- forwards a value
- barrel module
- distributes from one entry
- export * from
- forwards everything
- ./hello.js
- the source module