ESBuild Cheatsheet¶
ESBuild - Ein extrem schnelles JavaScript Bundler
ESBuild ist ein extrem schneller JavaScript-Bündler und Minifier. Es Pakete JavaScript und TypeScript-Code für die Verteilung auf dem Web, und ist in Go geschrieben, was macht es 10-100x schneller als andere Bündeler. < p>
Inhaltsverzeichnis¶
- [Installation](#installation
- (#basic-usage_)
- (#command-line-interface_)
- [JavaScript API](LINK_3__
- [Konfiguration](#configuration_
- (Entry Points)(LINK_5_)
- [Ausgang](LINK_6__
- (Loaders)(LINK_7_)
- (Plugins)(LINK_8_)
- [Außenabhängigkeiten](LINK_9_
- [Code Splitting](#code-splitting_
- (Tree Shaking)(LINK_11_)
- Quelle Maps
- (#watch-mode_)
- (#development-server_)
- [TypeScript Support](#typescript-support
- [JSX und React](LINK_16_
- CSS und Vermögenswerte
- [Optimierung](#optimization
- (#platform-targets)
- [Erweiterte Funktionen](#advanced-features
- [Performance](#performance_
- Beste Praktiken
Installation¶
Globale Installation¶
# Install ESBuild globally
npm install -g esbuild
# Check version
esbuild --version
```_
### Lokale Installation (empfohlen)
```bash
# Initialize npm project
npm init -y
# Install ESBuild locally
npm install --save-dev esbuild
# Or with Yarn
yarn add --dev esbuild
```_
### Paket.json Scripts
```json
{
"scripts": {
"build": "esbuild src/index.js --bundle --outfile=dist/bundle.js",
"dev": "esbuild src/index.js --bundle --outfile=dist/bundle.js --watch",
"serve": "esbuild src/index.js --bundle --outfile=dist/bundle.js --servedir=dist"
}
}
```_
## Basisnutzung
### Einfach zu bauen
```bash
# Bundle a single file
esbuild src/index.js --bundle --outfile=dist/bundle.js
# Minify the output
esbuild src/index.js --bundle --minify --outfile=dist/bundle.min.js
# Generate source maps
esbuild src/index.js --bundle --sourcemap --outfile=dist/bundle.js
```_
### Mehrere Entry Points
```bash
# Multiple files
esbuild src/home.js src/about.js --bundle --outdir=dist
# With different formats
esbuild src/index.js --bundle --format=esm --outfile=dist/index.esm.js
esbuild src/index.js --bundle --format=cjs --outfile=dist/index.cjs.js
esbuild src/index.js --bundle --format=iife --outfile=dist/index.iife.js
```_
### TypScript Support
```bash
# TypeScript files (no configuration needed)
esbuild src/index.ts --bundle --outfile=dist/bundle.js
# With type checking (requires tsc)
tsc --noEmit && esbuild src/index.ts --bundle --outfile=dist/bundle.js
```_
## Kommandozeilenschnittstelle
### Optionen erstellen
```bash
# Basic bundling
esbuild src/index.js --bundle --outfile=dist/bundle.js
# Output directory for multiple files
esbuild src/*.js --bundle --outdir=dist
# Minification
esbuild src/index.js --bundle --minify --outfile=dist/bundle.min.js
# Source maps
esbuild src/index.js --bundle --sourcemap --outfile=dist/bundle.js
esbuild src/index.js --bundle --sourcemap=inline --outfile=dist/bundle.js
esbuild src/index.js --bundle --sourcemap=external --outfile=dist/bundle.js
```_
### Format Optionen
```bash
# ES modules (default)
esbuild src/index.js --bundle --format=esm --outfile=dist/bundle.esm.js
# CommonJS
esbuild src/index.js --bundle --format=cjs --outfile=dist/bundle.cjs.js
# IIFE (Immediately Invoked Function Expression)
esbuild src/index.js --bundle --format=iife --outfile=dist/bundle.iife.js
# IIFE with global name
esbuild src/index.js --bundle --format=iife --global-name=MyLibrary --outfile=dist/bundle.js
```_
### Zieloptionen
```bash
# Target specific environments
esbuild src/index.js --bundle --target=es2020 --outfile=dist/bundle.js
esbuild src/index.js --bundle --target=node14 --outfile=dist/bundle.js
esbuild src/index.js --bundle --target=chrome90,firefox88 --outfile=dist/bundle.js
# Platform targeting
esbuild src/index.js --bundle --platform=browser --outfile=dist/bundle.js
esbuild src/index.js --bundle --platform=node --outfile=dist/bundle.js
esbuild src/index.js --bundle --platform=neutral --outfile=dist/bundle.js
```_
### Externe Abhängigkeiten
```bash
# Mark packages as external
esbuild src/index.js --bundle --external:react --external:react-dom --outfile=dist/bundle.js
# External with wildcards
esbuild src/index.js --bundle --external:@babel/* --outfile=dist/bundle.js
```_
### Ladeoptionen
```bash
# Specify loaders for file types
esbuild src/index.js --bundle --loader:.png=file --loader:.svg=text --outfile=dist/bundle.js
# Data URL loader
esbuild src/index.js --bundle --loader:.png=dataurl --outfile=dist/bundle.js
# Base64 loader
esbuild src/index.js --bundle --loader:.woff=base64 --outfile=dist/bundle.js
```_
## JavaScript API
### Basic Build API
```javascript
const esbuild = require('esbuild');
// Simple build
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js'
}).catch(() => process.exit(1));
// With async/await
async function build() {
try {
await esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
minify: true,
sourcemap: true
});
console.log('Build completed successfully');
} catch (error) {
console.error('Build failed:', error);
process.exit(1);
}
}
build();
```_
### Erweiterte Konfiguration erstellen
```javascript
const esbuild = require('esbuild');
const buildOptions = {
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
minify: process.env.NODE_ENV === 'production',
sourcemap: process.env.NODE_ENV !== 'production',
target: ['es2020', 'chrome90', 'firefox88'],
format: 'esm',
platform: 'browser',
external: ['react', 'react-dom'],
loader: {
'.png': 'file',
'.svg': 'text',
'.css': 'css'
},
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}
};
esbuild.build(buildOptions).catch(() => process.exit(1));
```_
### Mehrere Builds
```javascript
const esbuild = require('esbuild');
const builds = [
// ES module build
{
entryPoints: ['src/index.js'],
bundle: true,
format: 'esm',
outfile: 'dist/index.esm.js'
},
// CommonJS build
{
entryPoints: ['src/index.js'],
bundle: true,
format: 'cjs',
outfile: 'dist/index.cjs.js'
},
// IIFE build
{
entryPoints: ['src/index.js'],
bundle: true,
format: 'iife',
globalName: 'MyLibrary',
outfile: 'dist/index.iife.js'
}
];
Promise.all(builds.map(build => esbuild.build(build)))
.then(() => console.log('All builds completed'))
.catch(() => process.exit(1));
```_
## Konfiguration
### Konfigurationsdatei erstellen
```javascript
// build.js
const esbuild = require('esbuild');
const isDev = process.argv.includes('--dev');
const isWatch = process.argv.includes('--watch');
const config = {
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
minify: !isDev,
sourcemap: isDev,
target: ['es2020'],
format: 'esm',
platform: 'browser',
loader: {
'.png': 'file',
'.jpg': 'file',
'.svg': 'text',
'.css': 'css'
},
define: {
'process.env.NODE_ENV': JSON.stringify(isDev ? 'development' : 'production')
}
};
if (isWatch) {
esbuild.build({
...config,
watch: {
onRebuild(error, result) {
if (error) console.error('Watch build failed:', error);
else console.log('Watch build succeeded');
}
}
});
} else {
esbuild.build(config).catch(() => process.exit(1));
}
```_
### Umweltspezifische Konfiguration
```javascript
// esbuild.config.js
const esbuild = require('esbuild');
const createConfig = (env) => ({
entryPoints: ['src/index.js'],
bundle: true,
outfile: `dist/bundle.${env}.js`,
minify: env === 'production',
sourcemap: env === 'development',
target: env === 'production' ? ['es2018'] : ['es2020'],
define: {
'process.env.NODE_ENV': JSON.stringify(env),
'process.env.API_URL': JSON.stringify(
env === 'production'
? 'https://api.production.com'
: 'http://localhost:3000'
)
}
});
module.exports = { createConfig };
```_
## Eintrittspunkte
### Single Entry Point
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js'
});
```_
### Mehrere Entry Points
```javascript
esbuild.build({
entryPoints: ['src/home.js', 'src/about.js', 'src/contact.js'],
bundle: true,
outdir: 'dist'
});
```_
### Namensangaben
```javascript
esbuild.build({
entryPoints: {
home: 'src/pages/home.js',
about: 'src/pages/about.js',
admin: 'src/admin/index.js'
},
bundle: true,
outdir: 'dist'
});
```_
### Dynamische Eingangspunkte
```javascript
const glob = require('glob');
const entryPoints = glob.sync('src/pages/*.js').reduce((acc, file) => {
const name = file.replace('src/pages/', '').replace('.js', '');
acc[name] = file;
return acc;
}, {});
esbuild.build({
entryPoints,
bundle: true,
outdir: 'dist'
});
```_
## Ausgabe
### Ausgabedatei
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js'
});
```_
### Ausgabeverzeichnis
```javascript
esbuild.build({
entryPoints: ['src/home.js', 'src/about.js'],
bundle: true,
outdir: 'dist',
entryNames: '[name]-[hash]',
chunkNames: 'chunks/[name]-[hash]',
assetNames: 'assets/[name]-[hash]'
});
```_
### Öffentlicher Weg
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outdir: 'dist',
publicPath: '/static/'
});
```_
### Schreiben Sie die Erinnerung
```javascript
const result = await esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
write: false, // Don't write to disk
outdir: 'dist'
});
// Access output files
result.outputFiles.forEach(file => {
console.log(file.path, file.text);
});
```_
## Lastkraftwagen
### Einbaulader
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.js': 'js',
'.jsx': 'jsx',
'.ts': 'ts',
'.tsx': 'tsx',
'.css': 'css',
'.json': 'json',
'.txt': 'text',
'.png': 'file',
'.jpg': 'file',
'.gif': 'file',
'.svg': 'dataurl',
'.woff': 'base64',
'.woff2': 'base64'
}
});
```_
### Datei-Ladegerät
```javascript
// Copies files to output directory
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outdir: 'dist',
loader: {
'.png': 'file',
'.jpg': 'file',
'.gif': 'file'
}
});
// Usage in code
import logoUrl from './logo.png';
document.getElementById('logo').src = logoUrl;
```_
### Daten URL Loader
```javascript
// Embeds files as data URLs
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.svg': 'dataurl',
'.png': 'dataurl'
}
});
// Usage in code
import logo from './logo.svg'; // data:image/svg+xml;base64,...
```_
### Text geladen
```javascript
// Imports files as strings
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.txt': 'text',
'.md': 'text',
'.sql': 'text'
}
});
// Usage in code
import readme from './README.md';
console.log(readme); // String content
```_
### Base64 Loader
```javascript
// Imports files as base64 strings
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.woff': 'base64',
'.woff2': 'base64'
}
});
// Usage in code
import fontData from './font.woff2';
// Base64 encoded string
```_
## Plugins
### Plugin System
```javascript
// Simple plugin
const examplePlugin = {
name: 'example',
setup(build) {
build.onResolve({ filter: /^example:/ }, args => {
return { path: args.path, namespace: 'example' };
});
build.onLoad({ filter: /.*/, namespace: 'example' }, args => {
return {
contents: 'export default "This is from the example plugin"',
loader: 'js'
};
});
}
};
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
plugins: [examplePlugin]
});
```_
### Dateisystem Plugin
```javascript
const fs = require('fs');
const path = require('path');
const fileSystemPlugin = {
name: 'file-system',
setup(build) {
build.onResolve({ filter: /^fs:/ }, args => {
return {
path: path.resolve(args.resolveDir, args.path.slice(3)),
namespace: 'file-system'
};
});
build.onLoad({ filter: /.*/, namespace: 'file-system' }, args => {
const contents = fs.readFileSync(args.path, 'utf8');
return {
contents: `export default ${JSON.stringify(contents)}`,
loader: 'js'
};
});
}
};
// Usage: import content from 'fs:./data.txt';
```_
### HTTP Plugin
```javascript
const https = require('https');
const httpPlugin = {
name: 'http',
setup(build) {
build.onResolve({ filter: /^https?:\/\// }, args => {
return { path: args.path, namespace: 'http-url' };
});
build.onLoad({ filter: /.*/, namespace: 'http-url' }, args => {
return new Promise((resolve, reject) => {
https.get(args.path, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve({
contents: data,
loader: 'js'
}));
}).on('error', reject);
});
});
}
};
// Usage: import module from 'https://cdn.skypack.dev/lodash';
```_
### Umweltvariablen Plugins
```javascript
const envPlugin = {
name: 'env',
setup(build) {
build.onResolve({ filter: /^env$/ }, args => {
return { path: args.path, namespace: 'env' };
});
build.onLoad({ filter: /.*/, namespace: 'env' }, args => {
return {
contents: `export default ${JSON.stringify(process.env)}`,
loader: 'js'
};
});
}
};
// Usage: import env from 'env';
```_
## Externe Abhängigkeiten
### Basis extern
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
external: ['react', 'react-dom', 'lodash']
});
```_
### Außen mit Mustern
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
external: [
'react*', // react, react-dom, react-router, etc.
'@babel/*', // All @babel packages
'node:*' // Node.js built-in modules
]
});
```_
### Zustand extern
```javascript
const isProduction = process.env.NODE_ENV === 'production';
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
external: isProduction ? ['react', 'react-dom'] : []
});
```_
## Code Splitting
### Automatische Code Splitting
```javascript
esbuild.build({
entryPoints: ['src/home.js', 'src/about.js'],
bundle: true,
outdir: 'dist',
splitting: true,
format: 'esm' // Required for splitting
});
```_
### Dynamische Importe
```javascript
// main.js
async function loadModule() {
const { default: heavyModule } = await import('./heavy-module.js');
return heavyModule();
}
// ESBuild config
esbuild.build({
entryPoints: ['src/main.js'],
bundle: true,
outdir: 'dist',
splitting: true,
format: 'esm'
});
```_
### Manuelle Chunks
```javascript
// Use dynamic imports to create manual chunks
const loadUtils = () => import('./utils');
const loadComponents = () => import('./components');
// ESBuild will automatically create separate chunks
```_
## Tree Shaking
### Automatische Tree Shaking
```javascript
// ESBuild automatically tree-shakes ES modules
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
format: 'esm' // Required for tree shaking
});
```_
### Nebenwirkungen
```javascript
// package.json
{
"sideEffects": false // Enable aggressive tree shaking
}
// Or specify files with side effects
{
"sideEffects": [
"*.css",
"./src/polyfills.js"
]
}
```_
### Tree Shaking Beispiel
```javascript
// utils.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b; // This won't be included if not used
}
// main.js
import { add } from './utils.js'; // Only 'add' is bundled
console.log(add(2, 3));
```_
## Quelle Maps
### Optionen der Quellkarte
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
sourcemap: true // External source map
});
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
sourcemap: 'inline' // Inline source map
});
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
sourcemap: 'external' // External source map (same as true)
});
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
sourcemap: 'both' // Both inline and external
});
```_
### Quelle Map Konfiguration
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
sourcemap: true,
sourceRoot: '/src', // Source root in source map
sourcesContent: false // Don't include source content
});
```_
## Uhrmodus
### Basic Watch Mode
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
watch: true
});
```_
### Uhr mit Callbacks
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
watch: {
onRebuild(error, result) {
if (error) {
console.error('Watch build failed:', error);
} else {
console.log('Watch build succeeded:', result);
}
}
}
});
```_
### Erweiterte Uhrenkonfiguration
```javascript
const ctx = await esbuild.context({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js'
});
// Start watching
await ctx.watch();
// Stop watching later
await ctx.dispose();
```_
## Entwicklungsserver
### Basis-Entwicklungsserver
```bash
# Serve files from a directory
esbuild src/index.js --bundle --outfile=dist/bundle.js --servedir=dist
# Custom port
esbuild src/index.js --bundle --outfile=dist/bundle.js --servedir=dist --serve=8080
```_
### Entwicklung Server API
```javascript
const ctx = await esbuild.context({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js'
});
// Start development server
const { host, port } = await ctx.serve({
servedir: 'dist',
port: 3000
});
console.log(`Server running at http://${host}:${port}`);
```_
### Live Reload Setup
```javascript
const ctx = await esbuild.context({
entryPoints: ['src/index.js'],
bundle: true,
outdir: 'dist'
});
// Watch and serve
await Promise.all([
ctx.watch(),
ctx.serve({
servedir: 'dist',
port: 3000
})
]);
```_
## TypScript Support
### Haupttyp
```javascript
// No configuration needed for basic TypeScript
esbuild.build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/bundle.js'
});
```_
### TypeScript mit Typprüfung
```javascript
// ESBuild doesn't type-check, use tsc for that
const { execSync } = require('child_process');
// Type check first
try {
execSync('tsc --noEmit', { stdio: 'inherit' });
} catch (error) {
process.exit(1);
}
// Then build
esbuild.build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/bundle.js'
});
```_
### TypScript Konfiguration
```javascript
esbuild.build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/bundle.js',
target: 'es2020',
loader: {
'.ts': 'ts',
'.tsx': 'tsx'
}
});
```_
### Typologie Pfade
```javascript
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"]
}
}
}
// ESBuild doesn't resolve TypeScript paths automatically
// Use a plugin or resolve manually
const path = require('path');
esbuild.build({
entryPoints: ['src/index.ts'],
bundle: true,
outfile: 'dist/bundle.js',
plugins: [{
name: 'resolve-paths',
setup(build) {
build.onResolve({ filter: /^@\// }, args => {
return {
path: path.resolve('src', args.path.slice(2))
};
});
}
}]
});
```_
## JSX und React
### React JSX
```javascript
esbuild.build({
entryPoints: ['src/index.jsx'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.jsx': 'jsx'
},
jsx: 'automatic' // React 17+ automatic JSX
});
```_
### Benutzerdefinierte JSX
```javascript
esbuild.build({
entryPoints: ['src/index.jsx'],
bundle: true,
outfile: 'dist/bundle.js',
jsx: 'transform',
jsxFactory: 'h', // Preact
jsxFragment: 'Fragment'
});
```_
### JSX Entwicklung
```javascript
esbuild.build({
entryPoints: ['src/index.jsx'],
bundle: true,
outfile: 'dist/bundle.js',
jsx: 'automatic',
jsxDev: true, // Development mode
define: {
'process.env.NODE_ENV': '"development"'
}
});
```_
### TypScript + React
```javascript
esbuild.build({
entryPoints: ['src/index.tsx'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.tsx': 'tsx'
},
jsx: 'automatic'
});
```_
## CSS und Assets
### CSS Bund
```javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
loader: {
'.css': 'css'
}
});
// Import CSS in JavaScript
import './styles.css';
```_
### CSS Module (mit Plugin)
```javascript
const cssModulesPlugin = {
name: 'css-modules',
setup(build) {
build.onLoad({ filter: /\.module\.css$/ }, async (args) => {
// Implement CSS modules logic
const css = await fs.promises.readFile(args.path, 'utf8');
// Process CSS modules...
return {
contents: css,
loader: 'css'
};
});
}
};
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
plugins: [cssModulesPlugin]
});
Asset Handling¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outdir: 'dist',
loader: {
'.png': 'file',
'.jpg': 'file',
'.gif': 'file',
'.svg': 'file',
'.woff': 'file',
'.woff2': 'file'
},
assetNames: 'assets/[name]-[hash]'
});_
Optimierung¶
Bergbau¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
minify: true, // Minify JavaScript
minifyWhitespace: true,
minifyIdentifiers: true,
minifySyntax: true
});_
Tote Code Elimination¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
treeShaking: true, // Default for ES modules
format: 'esm'
});_
Feste Konstanten¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
define: {
'process.env.NODE_ENV': '"production"',
'DEBUG': 'false',
'VERSION': '"1.0.0"'
}
});_
Drop Console¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
drop: ['console', 'debugger']
});_
Plattform-Ziele¶
Browser Ziel¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
platform: 'browser',
target: ['chrome90', 'firefox88', 'safari14']
});_
Node.js Ziel¶
javascript
esbuild.build({
entryPoints: ['src/server.js'],
bundle: true,
outfile: 'dist/server.js',
platform: 'node',
target: 'node16',
external: ['fs', 'path', 'http'] // Node.js built-ins
});_
Neutrale Plattform¶
javascript
esbuild.build({
entryPoints: ['src/library.js'],
bundle: true,
outfile: 'dist/library.js',
platform: 'neutral', // Works in any environment
format: 'esm'
});_
Erweiterte Funktionen¶
Banner und Footer¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
banner: {
js: '/* My Library v1.0.0 */',
css: '/* Styles for My Library */'
},
footer: {
js: '/* End of bundle */'
}
});_
Inject Code¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
inject: ['./polyfills.js'] // Inject into every file
});_
Metafile Generation¶
```javascript const result = await esbuild.build({ entryPoints: ['src/index.js'], bundle: true, outfile: 'dist/bundle.js', metafile: true });
// Analyze bundle console.log(await esbuild.analyzeMetafile(result.metafile));
// Save metafile require('fs').writeFileSync('meta.json', JSON.stringify(result.metafile)); ```_
Bedingungen¶
javascript
esbuild.build({
entryPoints: ['src/index.js'],
bundle: true,
outfile: 'dist/bundle.js',
conditions: ['development'] // Package.json export conditions
});_
Leistung¶
Leistung steigern¶
```javascript // Measure build time const start = Date.now();
await esbuild.build({ entryPoints: ['src/index.js'], bundle: true, outfile: 'dist/bundle.js' });
console.log(Build took ${Date.now() - start}ms);
```_
Incremental Builds¶
```javascript const ctx = await esbuild.context({ entryPoints: ['src/index.js'], bundle: true, outfile: 'dist/bundle.js' });
// First build await ctx.rebuild();
// Subsequent rebuilds are faster await ctx.rebuild(); await ctx.rebuild();
// Clean up await ctx.dispose(); ```_
Parallel baut¶
```javascript const builds = [ esbuild.build({ entryPoints: ['src/client.js'], bundle: true, outfile: 'dist/client.js', platform: 'browser' }), esbuild.build({ entryPoints: ['src/server.js'], bundle: true, outfile: 'dist/server.js', platform: 'node' }) ];
await Promise.all(builds); ```_
Best Practices¶
Projektstruktur¶
```bash
Recommended structure¶
src/ ├── index.js # Main entry point ├── components/ # React components ├── utils/ # Utility functions ├── styles/ # CSS files ├── assets/ # Images, fonts, etc. └── types/ # TypeScript types ```_
Best Practices konfigurieren¶
```javascript // esbuild.config.js const esbuild = require('esbuild');
const isDev = process.env.NODE_ENV !== 'production';
const baseConfig = { entryPoints: ['src/index.js'], bundle: true, outdir: 'dist', sourcemap: isDev, minify: !isDev, target: ['es2020'], loader: { '.png': 'file', '.jpg': 'file', '.svg': 'file', '.css': 'css' }, define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development') } };
// Development config const devConfig = { ...baseConfig, watch: true, serve: { servedir: 'dist', port: 3000 } };
// Production config const prodConfig = { ...baseConfig, drop: ['console', 'debugger'], metafile: true };
module.exports = isDev ? devConfig : prodConfig; ```_
Leistungsoptimierung¶
- ** Verwenden Sie externe Abhängigkeiten** für Bibliotheken, die keine Bündelung benötigen
- Enable tree shaking mit ES-Modulen
- ** Verwenden Sie Code Splitting* für große Anwendungen
- Minimize Bündelgröße mit richtigen Ladegeräten
- Cache baut mit Inkrementalkompilation
Entwicklungs-Workflow¶
- Use Watch Mode für Entwicklung
- ** Quellkarten aktivieren* für Debugging
- ** Live-Reload einrichten* für bessere DX
- Typprüfung separat für TypeScript Projekte
- Verwendeter Entwicklungsserver für lokale Tests
Produktionsentwicklung¶
- Minify Code für kleinere Pakete
- Drop Konsolenaussagen für Reinigercode
- ** Generate Metafiles* für die Bündelanalyse
- **Verwendung von Inhalten ** für Caching
- ** Test baut** vor dem Einsatz
--
Zusammenfassung¶
ESBuild ist ein extrem schneller JavaScript-Bündler, der eine hervorragende Leistung mit minimaler Konfiguration bietet. Zu den wichtigsten Merkmalen gehören:
- Blazing Fast Speed: 10-100x schneller als andere Bündel
- **Zero Konfiguration*: Arbeiten aus der Box für die meisten Projekte
- **TypeScript Support*: Eingebaute TypeScript-Compilation
- Tree Shaking: Automatische Totcode-Beseitigung
- ** Code Splitting**: Unterstützung dynamischer Importe und Spaltung
- **Multiple Formate*: ES-Module, CommonJS, IIFE und mehr
- **Plugin System*: Erweiterbar mit benutzerdefinierten Plugins
- Entwicklungsserver: Eingebauter Entwicklungsserver mit Live-Reload
Durch den Einsatz der Geschwindigkeit und Einfachheit von ESBuild können Sie Ihre Bauzeiten deutlich verbessern und dabei alle Funktionen, die Sie für die moderne Webentwicklung benötigen, beibehalten.
<= <= <= <================================================================================= Funktion copyToClipboard() {\cHFFFF} const commands = document.querySelectorAll('code'); alle Befehle = ''; Befehle. Für jede(cmd) => alle Befehle += cmd.textContent + '\n'); navigator.clipboard.writeText (allCommands); Alarm ('Alle Befehle, die in die Zwischenablage kopiert werden!'); }
Funktion generierenPDF() { Fenster.print(); }