To aggregate modules means to import a number of related modules and export them together. This helps with code organisation and is sometimes known as a barrel module. There is a dedicated syntax for this in JavaScript.
For example, the default export of the SWR package is a React hook for data fetching. You can import it as follows:
import useSWR from "swr";
The hook expects a fetcher
function as its second argument, but the SWR package doesn’t actually provide one. You have to provide your own. In the Quick Start guide, they suggest a simple wrapper around the Fetch API:
const fetcher = (...args) => fetch(...args).then(res => res.json());
Whenever you use the hook, you need to provide the fetcher
function:
import useSWR from "swr";
const fetcher = (...args) => fetch(...args).then(res => res.json());
export default function Profile() {
const { data, error, isLoading } = useSWR("/api/user", fetcher);
// Conditionally render the UI...
}
You’ll probably need to use the fetcher
function across multiple files. You could move it into its own module, e.g. fetcher.js
:
const fetcher = (...args) => fetch(...args).then(res => res.json());
export default fetcher;
But this isn’t ideal. The two functions are tightly coupled and intended to be used together. It doesn’t really make sense to import them from separate modules:
import useSWR from "swr";
import fetcher from "./fetcher.js";
To fix this problem, you could aggregate the modules, e.g. in a file called swr.js
. Your first instinct might be to import the useSWR
hook, export it as the default export, and export the fetcher
function as a named export:
import useSWR from "swr";
export default useSWR;
export const fetcher = (...args) => fetch(...args).then(res => res.json());
This is fine, but you can do better! There’s a dedicated syntax for aggregation:
export { default } from "swr"; // Exports the default export of the SWR package
export const fetcher = (...args) => fetch(...args).then(res => res.json());
Now you can import the default and named exports from the same module. This makes it clear that they’re tightly coupled:
import useSWR, { fetcher } from "./swr.js";
Note that you’re importing from "./swr.js"
here, not "swr"
. The former is the path to the swr.js
module you created, relative to the current directory. The latter refers to the npm package in the node_modules/
directory.
For more on this topic, check out JavaScript modules > Aggregating modules in the MDN Web Docs.