### Basic esbuild-svelte Plugin Setup
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Demonstrates the fundamental configuration for integrating the esbuild-svelte plugin into an esbuild build process. Ensure esbuild and esbuild-svelte are installed.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
esbuild.build({
entryPoints: ["app.js"],
mainFields: ["svelte", "browser", "module", "main"],
conditions: ["svelte", "browser"],
bundle: true,
outfile: "out.js",
plugins: [sveltePlugin()],
});
```
--------------------------------
### Mount Svelte App in React-like Setup
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Example of mounting a Svelte component using the 'mount' function, similar to how one might integrate with a React application.
```javascript
import App from "./App.svelte";
import { mount } from "svelte";
mount(App, {
target: document.getElementById("app"),
});
```
--------------------------------
### Install esbuild
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Install esbuild as a development dependency if you encounter 'esbuild is not defined'.
```bash
npm install -D esbuild
```
--------------------------------
### Install esbuild-svelte and Dependencies
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Install esbuild, svelte, and esbuild-svelte as development dependencies.
```bash
npm install -D esbuild svelte esbuild-svelte
```
--------------------------------
### Custom esbuild Transform Options Example
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/utilities.md
An example demonstrating how to configure custom esbuild transform options within the `sveltePlugin`, highlighting which options are allowed and which would be ignored.
```javascript
sveltePlugin({
esbuildTsTransformOptions: {
// Allowed options
loader: "ts",
tsconfigRaw: { ... },
jsx: "preserve",
// These would be ignored:
// bundle: true, ← not allowed
// minify: true, ← not allowed
},
})
```
--------------------------------
### Custom Preprocessor Example
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/module-structure.md
Integrate a custom preprocessor by providing it to the sveltePlugin configuration.
```javascript
import myPreprocessor from "custom-preprocessor";
sveltePlugin({
preprocess: myPreprocessor,
})
```
--------------------------------
### Install Svelte Preprocessor
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Install `svelte-preprocess` if TypeScript is not compiling and configure it with the sveltePlugin.
```bash
npm install -D svelte-preprocess
```
```javascript
import { sveltePreprocess } from "svelte-preprocess";
sveltePlugin({
preprocess: sveltePreprocess(),
})
```
--------------------------------
### Install Svelte Module
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Install the Svelte module if you encounter 'Svelte is not defined'.
```bash
npm install svelte
```
--------------------------------
### Install Svelte Preprocessor
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Install the svelte-preprocess package to enable preprocessing features like TypeScript or SCSS.
```bash
npm install -D svelte-preprocess
```
--------------------------------
### Clone JavaScript Example with degit
Source: https://github.com/emh333/esbuild-svelte/blob/main/README.md
Use degit to quickly clone the JavaScript example from the repository to start a new Svelte project with esbuild.
```sh
# Clone the JavaScript example to get started
npx degit EMH333/esbuild-svelte/example-js my-svelte-app
```
--------------------------------
### Install esbuild-svelte and Dependencies
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Installs esbuild, svelte, and esbuild-svelte as development dependencies using npm.
```bash
npm install --save-dev esbuild svelte esbuild-svelte
```
--------------------------------
### Clone TypeScript Example with degit
Source: https://github.com/emh333/esbuild-svelte/blob/main/README.md
Use degit to quickly clone the TypeScript example from the repository to start a new Svelte project with esbuild.
```sh
# Clone the TypeScript example to get started
npx degit EMH333/esbuild-svelte/example-ts my-svelte-app
```
--------------------------------
### esbuild-svelte Plugin with Multiple Preprocessors
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Shows how to pass a pre-configured preprocessor instance to the esbuild-svelte plugin. This is useful when the preprocessor has its own complex setup.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
const preprocessors = sveltePreprocess();
esbuild.build({
entryPoints: ["app.js"],
bundle: true,
outdir: "./dist",
plugins: [
sveltePlugin({
preprocess: preprocessors,
}),
],
});
```
--------------------------------
### Define esbuild Plugin Structure
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
A basic esbuild plugin must return an object with a 'name' and a 'setup' function. The 'setup' function is invoked by esbuild with the PluginBuild object.
```typescript
export default function sveltePlugin(options?: esbuildSvelteOptions): Plugin {
return {
name: "esbuild-svelte",
setup(build) { ... }
};
}
```
--------------------------------
### Example Test Flow for esbuild-svelte
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/module-structure.md
Illustrates a typical test execution sequence involving temporary file creation, esbuild execution with the svelte plugin, incremental build testing, and verification of cache and error handling.
```javascript
// Create temp directory with test files
// Run esbuild with sveltePlugin
// Call rebuild() to test incremental builds
// Verify cache behavior and error handling
// Clean up
```
--------------------------------
### Basic esbuild-svelte Build Script
Source: https://github.com/emh333/esbuild-svelte/blob/main/README.md
A simple esbuild build script demonstrating the basic usage of the esbuild-svelte plugin. Ensure esbuild, Svelte, and esbuild-svelte are installed.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
esbuild
.build({
entryPoints: ["app.js"],
mainFields: ["svelte", "browser", "module", "main"],
conditions: ["svelte", "browser"],
bundle: true,
outfile: "out.js",
plugins: [sveltePlugin()],
logLevel: "info",
})
.catch(() => process.exit(1));
```
--------------------------------
### Verify esbuild-svelte Installation
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Verifies that the esbuild-svelte plugin is correctly installed and imported by checking its type.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
// Should not throw
console.log(typeof sveltePlugin); // "function"
```
--------------------------------
### Setup Compiler Options
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/utilities.md
Creates the final compiler options for the Svelte compiler. It sets a default for CSS to 'external' and then overrides it with any user-provided compiler options.
```typescript
let compilerOptions = {
css: "external" as "external", // Default
...opts.compilerOptions, // User options override
};
let moduleCompilerOptions: ModuleCompileOptions = {
...opts.moduleCompilerOptions,
};
```
--------------------------------
### Migrate Rollup Configuration to esbuild
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Convert Rollup configuration to an esbuild build script. This example shows the 'before' (Rollup) and 'after' (esbuild) configurations.
```javascript
// Before (Rollup)
import svelte from "rollup-plugin-svelte";
export default {
input: "src/app.js",
output: { file: "dist/app.js" },
plugins: [svelte()],
};
// After (esbuild)
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
await esbuild.build({
entryPoints: ["src/app.js"],
outdir: "dist",
bundle: true,
plugins: [sveltePlugin()],
});
```
--------------------------------
### esbuild-svelte Plugin with Svelte Preprocessing
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Shows how to configure the esbuild-svelte plugin to use svelte-preprocess for pre-processing Svelte components. Requires `svelte-preprocess` to be installed.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
esbuild.build({
entryPoints: ["index.js"],
bundle: true,
outdir: "./dist",
plugins: [
sveltePlugin({
preprocess: sveltePreprocess(),
}),
],
});
```
--------------------------------
### GitHub Actions CI/CD Workflow
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
A GitHub Actions workflow to automate building, installing dependencies, and testing on push or pull request events.
```yaml
name: Build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: "18"
- run: npm install
- run: npm run build
- run: npm test
```
--------------------------------
### Peer Dependencies: esbuild and Svelte
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/module-structure.md
Users are required to install esbuild and Svelte. These are not bundled with the plugin, allowing for independent upgrades.
```json
{
"esbuild": ">=0.17.0",
"svelte": ">=4.2.1 <6"
}
```
--------------------------------
### esbuild-svelte Plugin with SCSS Support
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Enables SCSS preprocessing for `
```
--------------------------------
### Recommended Project Layout
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Presents a more structured project layout for a Svelte application, including separate directories for components, pages, and stores.
```text
project/
├── src/
│ ├── app.js // Main entry
│ ├── app.svelte // Root component
│ ├── components/
│ │ ├── Button.svelte
│ │ └── Input.svelte
│ ├── pages/
│ │ ├── Home.svelte
│ │ └── About.svelte
│ ├── stores/
│ │ └── app.js
│ └── styles/
│ └── global.css
├── public/
│ └── index.html
├── build.js // esbuild config
├── package.json
├── tsconfig.json // If using TypeScript
└── dist/ // Output (generated)
```
--------------------------------
### Configure esbuild Plugin in build.js
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Set up the esbuild-svelte plugin in your build script.
```javascript
import svelte from 'esbuild-svelte';
await esbuild.build({
plugins: [svelte()],
// ... other options
});
```
--------------------------------
### Cache Invalidation Example
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
Shows a scenario where modifying a dependency (e.g., a SCSS file imported by a Svelte component) invalidates the cache for the component, triggering a recompile.
```javascript
// component.svelte imports style.scss
// Dependencies: [component.svelte, style.scss]
// Modify style.scss
// Cache for component.svelte is invalidated
// Next rebuild recompiles component.svelte
```
--------------------------------
### esbuild-svelte Plugin with TypeScript and Preprocessing
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Illustrates using the esbuild-svelte plugin with both TypeScript entry points and svelte-preprocess. Sets the `dev` option for the Svelte compiler.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
esbuild.build({
entryPoints: ["index.ts"],
bundle: true,
outdir: "./dist",
plugins: [
sveltePlugin({
preprocess: sveltePreprocess(),
compilerOptions: {
dev: true,
},
}),
],
});
```
--------------------------------
### Extract Line Text from Source
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/utilities.md
Extracts a specific line of text from the source code based on the start line number. This is a helper for formatting error messages.
```typescript
let lineText = source.split(/\r\n|\r|\n/g)[start.line - 1];
```
--------------------------------
### Run esbuild Watch Mode
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Command to execute the build script in watch mode.
```bash
node build.js --watch
```
--------------------------------
### Basic esbuild-svelte Plugin Initialization
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Initializes the esbuild-svelte plugin with default settings. Use this for standard Svelte compilation where CSS is externalized.
```javascript
sveltePlugin()
```
--------------------------------
### Monorepo Package Structure
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Illustrates a typical monorepo directory structure with separate packages for UI components and the main application.
```text
packages/
├── ui/
│ ├── src/
│ │ ├── Button.svelte
│ │ └── index.js
│ └── build.js
├── app/
│ ├── src/
│ │ ├── app.js
│ │ └── App.svelte
│ └── build.js
└── package.json
```
--------------------------------
### esbuild-svelte Plugin with Accessibility Warning Suppression
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Filters out specific accessibility warnings during the Svelte compilation process. This custom filter function prevents warnings starting with 'a11y-' from being reported.
```javascript
sveltePlugin({
filterWarnings: (warning) =>
!warning.code?.startsWith("a11y-"),
})
```
--------------------------------
### Enable esbuild Cache for Performance
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Enable the cache option in `sveltePlugin` to improve rebuild times.
```javascript
const ctx = await esbuild.context({
plugins: [sveltePlugin({ cache: true })],
});
```
--------------------------------
### Configure Svelte Preprocessor
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Integrate svelte-preprocess into your esbuild configuration.
```javascript
import sveltePreprocess from 'svelte-preprocess';
await esbuild.build({
plugins: [svelte({
preprocess: sveltePreprocess()
})],
// ... other options
});
```
--------------------------------
### Development Server with esbuild Context
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Integration of esbuild's context API with Node.js http server for live reloading during development.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
import { createServer } from "http";
import { readFileSync } from "fs";
const port = 3000;
const ctx = await esbuild.context({
entryPoints: ["src/app.js"],
outdir: "dist",
bundle: true,
sourcemap: true,
plugins: [sveltePlugin({ preprocess: sveltePreprocess() })],
});
await ctx.watch();
const server = createServer((req, res) => {
if (req.url === "/" || req.url === "/index.html") {
res.setHeader("Content-Type", "text/html");
res.end(readFileSync("public/index.html"));
} else {
const path = req.url.startsWith("/") ? req.url.slice(1) : req.url;
try {
res.end(readFileSync(`dist/${path}`));
} catch (e) {
res.statusCode = 404;
res.end("Not found");
}
}
});
server.listen(port, () => {
console.log(`Dev server running at http://localhost:${port}`);
});
```
--------------------------------
### Development Watch Mode with Caching
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/quick-reference.md
Enable caching for instant rebuilds of unchanged files during development watch mode. Subsequent rebuilds are fast.
```javascript
const ctx = await esbuild.context({
plugins: [sveltePlugin({ cache: true })],
});
while (true) {
await ctx.rebuild();
// Wait for file changes...
}
```
--------------------------------
### Add npm Scripts for Development and Build
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Configures package.json scripts to run the esbuild build process for development and production builds.
```json
{
"scripts": {
"dev": "node build.js",
"build": "node build.js"
}
}
```
--------------------------------
### Pre-commit Hook Configuration
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Configures `husky` and `lint-staged` to run ESLint and a build check on staged JavaScript and Svelte files before committing.
```json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,svelte}": ["eslint", "node build.js --check"]
}
}
```
--------------------------------
### Enable Watch Mode for Development
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Configure esbuild to use context and watch mode for rapid development and hot rebuilds.
```javascript
const context = await esbuild.context({
plugins: [svelte()],
// ... other options
});
await context.watch();
```
--------------------------------
### Enable Caching for Fast Incremental Builds
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Use the 'cache: true' option to speed up incremental builds during development.
```javascript
const context = await esbuild.context({
plugins: [svelte({
cache: true
})],
// ... other options
});
```
--------------------------------
### Register Multiple esbuild Hook Instances
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
Demonstrates how to register multiple instances of hooks like onLoad and onResolve, often using filters and namespaces to target specific files or modules.
```typescript
// All hooks can register multiple times for different filters
build.onLoad({ filter: svelteFilter }, callback1);
build.onLoad({ filter: cssFilter, namespace: "fakecss" }, callback2);
build.onResolve({ filter: cssFilter }, callback3);
build.onEnd(callback4);
```
--------------------------------
### Project File Structure
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/INDEX.md
This snippet displays the directory structure of the esbuild-svelte project, showing the organization of markdown documentation files and API reference subdirectories.
```text
/workspace/home/output/
├── INDEX.md (this file)
├── README.md
├── TABLE_OF_CONTENTS.md
├── DOCUMENTATION_MANIFEST.md
├── quick-reference.md
├── integration-guide.md
├── configuration.md
├── types.md
├── errors.md
├── advanced-patterns.md
└── api-reference/
├── sveltePlugin.md
├── plugin-implementation.md
├── preprocessing.md
├── module-structure.md
└── utilities.md
```
--------------------------------
### esbuild Build Script with Watch Mode
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
A build script configured to use esbuild's context API for enabling watch mode, allowing for incremental rebuilds on file changes.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
const isWatch = process.argv.includes("--watch");
const ctx = await esbuild.context({
entryPoints: ["src/app.js"],
outdir: "dist",
bundle: true,
sourcemap: true,
plugins: [
sveltePlugin({
preprocess: sveltePreprocess(),
cache: true, // Enable for faster rebuilds
}),
],
});
if (isWatch) {
await ctx.watch();
console.log("Watching for changes...");
} else {
await ctx.rebuild();
await ctx.dispose();
}
```
--------------------------------
### Import and Use sveltePlugin
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Import the default export function and use it to create an esbuild plugin. The plugin can be configured with an options object.
```typescript
import sveltePlugin from "esbuild-svelte";
// Usage with default options
const plugin = sveltePlugin();
// Usage with custom options
const customPlugin = sveltePlugin({
compilerOptions: {
// Svelte compiler options
},
// Other esbuild-svelte options
});
```
--------------------------------
### package.json Configuration for esbuild-svelte
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/module-structure.md
Defines the entry points for different module systems (ESM, CommonJS), type definitions, and specifies which files are published to npm. Only the 'dist/' directory and CHANGELOG.md are included in the published package.
```json
{
"module": "dist/index.mjs", // ESM entry point
"main": "dist/index.js", // CommonJS entry point
"types": "dist/index.d.ts", // Type definitions
"files": ["/dist", "/CHANGELOG.md"] // What gets published
}
```
--------------------------------
### Build Script with TypeScript and Svelte Preprocessing
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Configuration for esbuild to handle TypeScript files and Svelte components using svelte-preprocess.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
await esbuild.build({
entryPoints: ["src/app.ts"],
outdir: "dist",
bundle: true,
plugins: [
sveltePlugin({
preprocess: sveltePreprocess(),
}),
],
});
```
--------------------------------
### Configure esbuild Build Options for Svelte
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/configuration.md
Use `mainFields` and `conditions` in your esbuild build configuration to correctly resolve Svelte component libraries. Ensure 'svelte' is included in both arrays.
```javascript
esbuild.build({
// esbuild options
mainFields: ["svelte", "browser", "module", "main"],
conditions: ["svelte", "browser"],
// plugin options
plugins: [sveltePlugin({ /* options */ })],
})
```
--------------------------------
### Return Dependencies for Watch Mode
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/plugin-implementation.md
Provides the list of tracked dependencies to esbuild for watch mode to monitor file changes.
```typescript
result.watchFiles = Array.from(dependencyModificationTimes.keys());
```
--------------------------------
### Build Script with SCSS Support
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
esbuild configuration to enable SCSS preprocessing within Svelte components using svelte-preprocess and the 'sass' implementation.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
import { sveltePreprocess } from "svelte-preprocess";
import sass from "sass";
await esbuild.build({
entryPoints: ["src/app.js"],
outdir: "dist",
bundle: true,
plugins: [
sveltePlugin({
preprocess: sveltePreprocess({
scss: {
impl: sass,
},
}),
}),
],
});
```
--------------------------------
### Understand esbuild Hook Callback Signatures
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
Illustrates the expected signatures for common esbuild hooks like onLoad, onResolve, and onEnd. These hooks can be asynchronous and return promises.
```typescript
// onLoad callback
(args: OnLoadArgs) => OnLoadResult | Promise | null
// onResolve callback
(args: OnResolveArgs) => OnResolveResult | Promise | null
// onEnd callback
(result: BuildResult) => Promise | void
```
--------------------------------
### Incremental Build Error Recovery with esbuild-svelte
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/errors.md
Implement a loop to continuously rebuild with esbuild and handle potential errors gracefully. This pattern allows watch mode to recover from build failures and recompile when files are fixed.
```javascript
const ctx = await esbuild.context({
plugins: [sveltePlugin({ cache: true })],
});
while (true) {
try {
await ctx.rebuild();
console.log("Build successful");
} catch (err) {
console.error("Build failed:", err.errors);
// File will be recompiled on next rebuild
}
// Wait for file changes...
}
```
--------------------------------
### Chained esbuild Builds
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
Perform a two-stage build process with esbuild. The first build compiles to an intermediate format, and the second build performs further processing like minification.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
// First build: compile to intermediate form
await esbuild.build({
entryPoints: ["src/app.js"],
outdir: "dist/intermediate",
plugins: [sveltePlugin()],
});
// Second build: further processing, minification, etc.
await esbuild.build({
entryPoints: ["dist/intermediate/app.js"],
outdir: "dist/final",
minify: true,
});
```
--------------------------------
### Using File Filters in onLoad Hook
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/utilities.md
Demonstrates how to use Svelte file filters within an esbuild `onLoad` hook to conditionally handle different file types.
```typescript
build.onLoad({ filter: svelteFilter }, async (args) => {
const filename = relative(process.cwd(), args.path);
// Check file type
if (SVELTE_TYPESCRIPT_MODULE_FILTER.test(filename)) {
// Handle .svelte.ts
} else if (SVELTE_JAVASCRIPT_MODULE_FILTER.test(filename)) {
// Handle .svelte.js
} else {
// Handle .svelte
}
});
```
--------------------------------
### Initialize Dependency Tracking Map
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/plugin-implementation.md
Initializes a map to store modification times of files for dependency tracking in watch mode.
```typescript
const dependencyModificationTimes = new Map();
```
--------------------------------
### Activate Smart Caching for Subsequent Builds
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/plugin-implementation.md
This snippet configures the caching behavior. On the first build, if `opts.cache` is undefined, it's set to `true`. This ensures caching is enabled automatically for all subsequent builds, optimizing incremental and watch builds while avoiding overhead for one-shot builds.
```typescript
build.onEnd(() => {
if (opts.cache === undefined) {
opts.cache = true;
}
});
```
--------------------------------
### Reporting Dependencies in Watch Mode
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
Reports all dependencies, including the input file and preprocessor imports, to esbuild for monitoring. This ensures that esbuild can trigger rebuilds when any relevant file changes.
```typescript
result.watchFiles = Array.from(dependencyModificationTimes.keys());
return result;
```
--------------------------------
### Large Projects with Caching and Immutability
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/quick-reference.md
Configure caching and compiler options for large projects. Caching is always enabled, and Svelte can skip immutability checks.
```javascript
sveltePlugin({
cache: true, // Always cache (even for one-shot if you rebuild multiple times)
compilerOptions: {
immutable: true, // Svelte can skip immutability checks
},
})
```
--------------------------------
### sveltePlugin
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Creates an esbuild plugin for compiling Svelte components. It handles Svelte files, TypeScript modules, and CSS generation, with support for caching and preprocessing.
```APIDOC
## sveltePlugin
### Description
Creates an esbuild plugin configured to handle Svelte component compilation. This plugin integrates with esbuild's API to manage file loading, Svelte compilation, TypeScript transformation, external CSS handling, and build caching.
### Function Signature
```typescript
export default function sveltePlugin(options?: esbuildSvelteOptions): Plugin
```
### Parameters
#### Parameters
- **options** (`esbuildSvelteOptions`) - Optional - `{}` - Configuration object for the plugin behavior and Svelte compiler options.
### Return Type
`Plugin` — An esbuild plugin object with `name: "esbuild-svelte"`.
```
--------------------------------
### Initialize Cache Storage Maps
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/utilities.md
Initializes two Map objects for caching CSS code and compiled file data. `cssCode` stores CSS content by a fake path, and `fileCache` stores compilation results indexed by the file's absolute path.
```typescript
const cssCode = new Map();
const fileCache = new Map();
```
--------------------------------
### Configure esbuild for CSS
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Configure `mainFields` and `conditions` in your esbuild build to ensure CSS is correctly processed.
```javascript
esbuild.build({
mainFields: ["svelte", "browser", "module", "main"],
conditions: ["svelte", "browser"],
plugins: [sveltePlugin()],
})
```
--------------------------------
### Build Script for In-Browser CSS Injection
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
esbuild configuration to compile Svelte components with CSS processed and injected directly into the JavaScript bundle.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
await esbuild.build({
entryPoints: ["src/app.js"],
outdir: "dist",
bundle: true,
plugins: [
sveltePlugin({
compilerOptions: {
css: "injected", // CSS included in JS
},
}),
],
});
```
--------------------------------
### Production One-Shot Build
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/quick-reference.md
Disable caching for a fast initial build in production. This avoids caching overhead for single builds.
```javascript
esbuild.build({
plugins: [sveltePlugin()], // cache: undefined → caching disabled
});
```
--------------------------------
### Configure Multiple Svelte Preprocessors
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/configuration.md
Use an array of Svelte preprocessors to apply multiple transformations in sequence to component source code. This allows for complex preprocessing pipelines, such as combining svelte-preprocess with custom preprocessors. Preprocessors are only applied to .svelte files.
```javascript
import { sveltePreprocess } from "svelte-preprocess";
import customPreprocessor from "custom-preprocessor";
sveltePlugin({
preprocess: [sveltePreprocess(), customPreprocessor],
})
```
--------------------------------
### Add Build Script to package.json
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Define an npm script to run your esbuild build process.
```json
{ "scripts": {
"build": "node build.js"
}
}
```
--------------------------------
### HTML Structure for Svelte App
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Basic HTML file structure to host a Svelte application, including a target div and script tags for the bundled JavaScript.
```html
My Svelte App
```
--------------------------------
### Source Map Composition with Trace Mapping
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/advanced-patterns.md
This snippet illustrates how to use `@jridgewell/trace-mapping` to compose source maps from different transformation stages (preprocessor and Svelte compiler). This allows debugging original source code even after multiple compilations.
```typescript
if (preprocessResult.map) {
// Svelte compiler has the map
// When Svelte reports error at line 15, column 5
// Plugin traces back through preprocessor map
// to find original position in SCSS
}
```
--------------------------------
### esbuild-Svelte Watch Mode with Caching
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/README.md
Enable watch mode with caching for faster rebuilds during development. The `context` API is used to manage the build state.
```javascript
const ctx = await esbuild.context({
entryPoints: ["app.js"],
bundle: true,
outdir: "./dist",
plugins: [sveltePlugin({ cache: true })],
});
await ctx.rebuild(); // Compile
// ... file changes ...
await ctx.rebuild(); // Fast! Cache hits
```
--------------------------------
### Build Svelte Component as Web Component
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Builds a Svelte component as a custom element (web component) using esbuild and esbuild-svelte. Ensure `customElement: true` is set in compiler options.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
await esbuild.build({
entryPoints: ["src/Button.svelte"],
outdir: "dist",
bundle: true,
plugins: [
sveltePlugin({
compilerOptions: {
customElement: true, // Export as web component
},
}),
],
});
```
--------------------------------
### Add Input File to Dependencies
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/plugin-implementation.md
Adds the main input file to the dependency tracking map with its modification time.
```typescript
dependencyModificationTimes.set(args.path, statSync(args.path).mtime);
```
--------------------------------
### Enable Caching for Development Builds
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/integration-guide.md
Use `cache: true` in the svelte-esbuild plugin for instant rebuilds of unchanged files during development watch mode.
```javascript
const ctx = await esbuild.context({
plugins: [sveltePlugin({ cache: true })],
});
await ctx.watch(); // Instant rebuilds for unchanged files
```
--------------------------------
### Add Preprocessor Dependencies
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/plugin-implementation.md
Adds files identified as preprocessor dependencies to the tracking map.
```typescript
preprocessResult.dependencies?.forEach((entry) => {
dependencyModificationTimes.set(entry, statSync(entry).mtime);
});
```
--------------------------------
### esbuild-svelte Plugin with Warning Filtering
Source: https://github.com/emh333/esbuild-svelte/blob/main/_autodocs/api-reference/sveltePlugin.md
Demonstrates how to filter build warnings using a custom function provided to `filterWarnings`. This allows suppressing specific types of warnings.
```javascript
import esbuild from "esbuild";
import sveltePlugin from "esbuild-svelte";
esbuild.build({
entryPoints: ["app.js"],
bundle: true,
outdir: "./dist",
plugins: [
sveltePlugin({
filterWarnings: (warning) => {
// Suppress specific warnings (e.g., unused CSS class)
return !warning.message.includes("unused");
},
}),
],
});
```