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.
esbuild has a built-in text loader, but a plugin shows the extension point and lets you change the contents as they load.
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] });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.