JavaScript, how to export multiple functions
By Flavio Copes
Learn how to export multiple functions from a JavaScript file with a named export like export { sum, mul }, then import them all or just the ones you need.
To export multiple functions from a JavaScript file, you use a named export: list the functions in curly braces after the export keyword. Other files can then import all of them, or just the ones they need.
This is how we split a program into separate files. Each file keeps its functions private until we explicitly export them.
You typically write a few functions, like this:
function sum(a, b) {
return a + b
}
function mul(a, b) {
return a * b
}
and you can make them available for any other file using this syntax:
export { sum, mul }
I like this style because the export list at the bottom acts as a summary of the file’s public interface.
The files that need the functionality exported will import all the functions, or just the ones they need:
import { sum, mul } from 'myfile'
import { mul } from 'myfile'
In a real project the path is usually relative, like './myfile.js'.
Exporting inline
Alternatively, you can put export directly in front of each function declaration:
export function sum(a, b) {
return a + b
}
export function mul(a, b) {
return a * b
}
The result is the same. Pick one style and stick with it in a codebase.
Renaming on import
Named imports must match the exported names. If a name clashes with something you already have, rename it with as:
import { sum as addNumbers } from './myfile.js'
addNumbers(1, 2) //3
You can also rename on the export side, with export { sum as add }.
Mixing with a default export
A file can have many named exports, but only one default export. You can combine them:
export default sum
export { mul }
and import both in one line:
import sum, { mul } from './myfile.js'
A common pitfall
The export keyword only works in ES modules. If you run a file like this with Node and it’s treated as CommonJS, you’ll get SyntaxError: Unexpected token 'export'.
The fix is to add "type": "module" to your package.json, or rename the file to use the .mjs extension. In the browser, load the file with <script type="module">.
Related posts about js: