There are two ways to export from a module in JavaScript. These are default and named exports. You can use them together if needed!
Default export
If you need to export one main 'thing' from a module, you can use a default export. In the following example, we fetch data from an API (using top-level await) and export it from the module:
const API = "https://jsonplaceholder.typicode.com/users";
let users;
async function getJSON(response) {
if (response.ok) {
const data = await response.json();
return Promise.resolve(data);
}
const { status, statusText } = response;
const error = new Error(`${status} ${statusText}`);
return Promise.reject(error);
}
try {
const response = await fetch(API);
users = await getJSON(response);
} catch (error) {
users = error;
}
export default users;
In another module, we could import the users
data like so:
import users from "./users.js";
Named exports
There's other useful stuff in our module, such as the API
constant and the getJSON()
function. We could export these as named exports:
export { API, getJSON };
In another module, we could import these like so:
import { API, getJSON } from "./users.js";
Default and named exports
We could export the default users
data and the named utilities like so:
export { users as default, API, getJSON };
In another module, we could import the default export and the named exports like this:
import users, { API, getJSON } from "./users.js";
If you've used React before, this probably looks familiar. This is how you import the main React library along with some hooks:
import React, { useState, useEffect } from "react";