esbuild-plugin-preserve-directives

raw JSON →
0.0.11 verified Fri May 01 auth: no javascript

An esbuild plugin that ensures directives like 'use client' and 'use strict' are preserved at the top of output files. Current stable version is 0.0.11. The plugin scans source files for specified directives before bundling and reinserts them into the corresponding output chunks. It supports regex-based include/exclude patterns and works with esbuild's metafile option for improved accuracy. Updated frequently with community contributions, it is primarily used with React Server Components and Node.js ESM/CJS builds. Key differentiator: it handles directives that esbuild would otherwise strip, with minimal overhead.

error Error: The plugin 'esbuild-plugin-preserve-directives' must be used with esbuild ^0.21.0
cause Peer dependency version mismatch
fix
Run 'npm install esbuild@^0.21.0' or update esbuild to compatible version.
error Cannot find module 'esbuild-plugin-preserve-directives'
cause Package not installed
fix
Run 'npm install -D esbuild-plugin-preserve-directives'.
error Uncaught TypeError: preserveDirectivesPlugin is not a function
cause Default import used instead of named import
fix
Use 'import { preserveDirectivesPlugin } from 'esbuild-plugin-preserve-directives''.
gotcha metafile option is not required but strongly recommended for accuracy; without it, directive preservation may be incomplete.
fix Add metafile: true to esbuild options.
breaking Plugin requires esbuild ^0.21.0; older esbuild versions are incompatible.
fix Upgrade esbuild to ^0.21.0 or later.
deprecated Node.js <18.0.0 is not supported.
fix Use Node.js >=18.0.0.
npm install esbuild-plugin-preserve-directives
yarn add esbuild-plugin-preserve-directives
pnpm add esbuild-plugin-preserve-directives

Shows how to use the plugin with esbuild, including metafile option for accuracy.

import { build } from 'esbuild';
import { preserveDirectivesPlugin } from 'esbuild-plugin-preserve-directives';

await build({
  entryPoints: ['src/index.js'],
  bundle: true,
  outdir: 'dist',
  metafile: true,
  plugins: [
    preserveDirectivesPlugin({
      directives: ['use client', 'use strict'],
      include: /\.(js|ts|jsx|tsx)$/,
      exclude: /node_modules/,
    }),
  ],
});