Follow these steps to generate a single-file 'ESM' (ECMAScript Module) package using Node.js and ESBuild:
1. Install ESBuild
First, ensure Node.js is installed, then install ESBuild using npm or yarn:
bashnpm install esbuild --save-dev
or
bashyarn add esbuild --dev
2. Prepare Source Code
Assume your project structure is similar to:
shell/your-project /src index.js
In src/index.js, add code in ES Module format, for example:
javascriptexport function sayHello(name) { return `Hello, ${name}!`; }
3. Configure ESBuild
Create a build script file, such as build.js, to configure ESBuild for bundling your code:
javascriptconst esbuild = require('esbuild'); esbuild.build({ entryPoints: ['src/index.js'], bundle: true, format: 'esm', // Specify output format as ESM outfile: 'dist/bundle.js', }).catch(() => process.exit(1));
4. Run the Build Script
Execute your build script using Node.js:
bashnode build.js
This command generates a bundled file in dist/bundle.js.
5. Check the Output
In dist/bundle.js, you will see all code bundled into a single file and exported in ESM format. This creates a single-file ESM package.
6. Use the ESM Package
Import this package in other projects using ESM:
javascriptimport { sayHello } from './path/to/dist/bundle.js'; console.log(sayHello('World'));
The steps above outline how to create a single-file ESM package using Node.js and ESBuild. This approach allows you to easily bundle multiple JavaScript files and modules into a single file for convenient import and usage across different JavaScript environments.