rollup-plugin-preserve-directives
raw JSON → 0.4.0 verified Mon Apr 27 auth: no javascript
A Rollup plugin that preserves file-level directives (e.g., 'use client', 'use server') when using preserveModules: true. Version 0.4.0 is the current stable release, with a simple API and minimal configuration. Unlike bundling, where directives are meaningless per file, this plugin ensures each preserved module retains its directives, enabling patterns like React Server Components without separate entrypoints. Still considered early-stage (largely untested) but functional. Filters via include/exclude globs. Warning suppression options exist. Supports Rollup 2–4. Ships TypeScript types.
Common errors
error Module level directives cause errors when bundled, 'use client' was ignored. ↓
cause preserveModules is not enabled, or the plugin is not used.
fix
Set output.preserveModules: true and add preserveDirectives() to the plugins array.
error preserveModules must be true for preserveDirectives to work. ↓
cause The plugin is used but preserveModules is not set to true.
fix
Set output.preserveModules: true in your Rollup config.
error Directive 'use client' was removed after minification. ↓
cause Terser or other minifier removes directives by default.
fix
Configure minifier to preserve directives, e.g., terser({ compress: { directives: false } }).
Warnings
gotcha preserveModules must be true for the plugin to work; otherwise it warns and does nothing. ↓
fix Set output.preserveModules: true in your Rollup config.
gotcha Minifiers like terser may remove directives; terser's compress.directives defaults to true. ↓
fix Set terser compress.directives: false to preserve directives.
deprecated suppressPreserveModulesWarning option exists but will be removed in future versions. ↓
fix Avoid using suppressPreserveModulesWarning; use onwarn in Rollup to handle warnings.
gotcha Rollup still emits warnings about module-level directives; the plugin does not suppress them. ↓
fix Add an onwarn handler to ignore directive warnings, e.g., onwarn: (warning, defaultHandler) => { if (!warning.message.includes('use client')) defaultHandler(warning); }
Install
npm install rollup-plugin-preserve-directives yarn add rollup-plugin-preserve-directives pnpm add rollup-plugin-preserve-directives Imports
- preserveDirectives wrong
import { preserveDirectives } from 'rollup-plugin-preserve-directives'correctimport preserveDirectives from 'rollup-plugin-preserve-directives' - preserveDirectives wrong
const { preserveDirectives } = require('rollup-plugin-preserve-directives')correctconst preserveDirectives = require('rollup-plugin-preserve-directives') - type Options
import type { Options } from 'rollup-plugin-preserve-directives'
Quickstart
// rollup.config.js
import preserveDirectives from 'rollup-plugin-preserve-directives';
export default {
input: 'src/index.js',
output: {
dir: 'dist',
format: 'esm',
preserveModules: true,
},
plugins: [
preserveDirectives({
exclude: ['**/*.css'],
}),
],
};