乐闻世界logo
搜索文章和话题

How to generate a single file "ESM" bundle using ESBuild for Node.js?

1个答案

1

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:

bash
npm install esbuild --save-dev

or

bash
yarn 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:

javascript
export 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:

javascript
const 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:

bash
node 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:

javascript
import { 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.

2024年8月10日 01:03 回复

你的答案