Skip to content
jshacks.dev
Tooling

Write an esbuild plugin to load text files

Load .txt files as strings in an esbuild bundle with a small plugin that reads the file in an onLoad hook.

1 min read
Summarize in AI

esbuild has a built-in text loader, but a plugin shows the extension point and lets you change the contents as they load.

build.mjsJavaScript
import { build } from 'esbuild';
import { readFile } from 'node:fs/promises';

const textPlugin = {
  name: 'text-files',
  setup(build) {
    build.onLoad({ filter: /\.txt$/ }, async (args) => {
      const text = await readFile(args.path, 'utf8');
      return { contents: `export default ${JSON.stringify(text.trim())};`, loader: 'js' };
    });
  },
};

await build({ entryPoints: ['src/main.js'], bundle: true, outfile: 'out.js', plugins: [textPlugin] });
src/main.jsJavaScript
import notice from './notice.txt';
console.log(notice);

onLoad runs for every file whose path matches the filter and returns the replacement module source. Here the text becomes a JSON string in a default export, so import notice from './notice.txt' gives the file's content. The filter is a Go regular expression, which is why it must stay simple. See the esbuild plugin docs.

If you only need the text, skip the plugin and write loader: { '.txt': 'text' } in the build options. Choose a plugin when the contents need processing.

Share

More snippets

Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read
Tooling

Configure VS Code settings for a team

Share VS Code settings and recommended extensions with a team by committing a .vscode folder with settings.json and extensions.json.

1 min read
Tooling

Share an ESLint config across packages

Share one ESLint 9 flat config across workspace packages by exporting an array from a package and spreading it into each package's eslint.config.js.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.