DEV Community

Cover image for esbuild Ignore With Comments Plugin
Max Rohde
Max Rohde

Posted on • Originally published at maxrohde.com

esbuild Ignore With Comments Plugin

With the increasing popularity of full stack frameworks that combine server-side and client-side code, build tools need to support selectively including or ignoring files in a project.

When developing a framework for React Serverless SSR Rendering, I needed the capability to prevent certain code from being packaged up for the server or client. Specifically, server-side logic that required dependencies incompatible with client-side JavaScript (such as fs) would result in my client-side build to break.

While esbuild provides a number of tools to exclude certain files or dependencies, I found these insufficient for my needs and thus developed the esbuild-ignore-with-comments-plugin.

This plugin allows to add a comment as the following to a source file:

/* esbuild-ignore */
Enter fullscreen mode Exit fullscreen mode

All content in this file with subsequently be ignored by esbuild when the plugin is configured as follows:

import ignorePlugin from 'esbuild-ignore-with-comments-plugin';
import { build } from 'esbuild';

await build({
  plugins: [ignorePlugin()],
});
Enter fullscreen mode Exit fullscreen mode

It is further possible to support multiple esbuild build configurations over the same codebase by adding a qualifier to the comment, such as:

/* esbuild-ignore ui */
Enter fullscreen mode Exit fullscreen mode

Then files will be ignored in a build with the plugin configured as follows:

await build({
  plugins: [ignorePlugin(['ui'])],
});
Enter fullscreen mode Exit fullscreen mode

For instance, this plugin is used in the project React Server-Side Rendering ( react-ssr) as follows:

  • The file _document.ts is only required during Server-Side rendering to assemble the HTML document. Thus, the comment /* esbuild-ignore ui */ is added:
/* esbuild-ignore ui */

import type { RenderDocumentProps } from '@goldstack/template-ssr';

const renderDocument = async (props: RenderDocumentProps<unknown>): Promise<string> => {
// ...
}
Enter fullscreen mode Exit fullscreen mode
  • The file build.ts is required only to define the configuration for esbuild itself. It does not need to be bundled for the client or server. Thus, comments to ignore this file for both server-side and client-side builds are provided:
/* esbuild-ignore ui */
/* esbuild-ignore server */

import { pnpPlugin } from '@yarnpkg/esbuild-plugin-pnp';
import cssPlugin from 'esbuild-css-modules-client-plugin';
import ignorePlugin from 'esbuild-ignore-with-comments-plugin';

// ...
Enter fullscreen mode Exit fullscreen mode

If you have any question or comments, please reach out or raise an issue 🤗.

Top comments (0)