This video is available to students only

Building Multiple JS Modules

Updating ESBuild to export multiple JS module formats.

There are cases when we want to export multiple module types. Scroller will expose CJS and ESM module formats. This allows consumers of Scroller to use older versions of NodeJS to import the CJS build, or newer NodeJS versions to import ESM. When Scroller is used directly in the browser, users can use the ESM build.

Setting up ESBuild with JavaScript#

We first set up ESBuild using a package.json script that runs ESBuild's CLI. To achieve multiple builds we'll create a NodeJS build script called esbuild.js.

At the root of our Scroller project, create a new file called esbuild.js.

An image showing an esbuild build file created in the Scroller directory.

Inside esbuild.js import the ESBuild library using CJS require() syntax. Call the build function using similar parameters to our build package.json script.

NodeJS requires files to use the .mjs extension, or update parameters in package.json to enable ESM modules. To avoid having to configure NodeJS, we'll stick to CJS for any build tool configuration. The code above will look similar to our package.json build script (esbuild ./src/index.js --bundle --format=esm --outdir=dist).

We tell ESBuild to build our code found at src/index.js as an ESM module, then put the bundled code into a dist directory.

Setting up multiple module outputs#

 

This page is a preview of Creating React Libraries from Scratch

No discussions yet