Troubleshooting

Issues you might face when using esbuild-azure-functions and how to solve them

ReferenceError: [__dirname|__filename] is not defined in ES module scope

This error stems from the fact that __dirname and __filename are not present in an ESM environment. To fix this, simply set advancedOptions.enableDirnameShim to true (see config)

Error: Dynamic require of "xyz" is not supported

This error stems from esbuild not being able to convert CJS requires to ESM imports. This happens mostly (from what I've seen) with Node.js internals (like http, crypto and so on). To fix this issue you have the following options:

Turn off code splitting

Then you also need to change the format to cjs (not recommended because it increases the bundle size exponentially)

build.mjs
import { build } from 'esbuild-azure-functions';

await build({
  project: '.',
  clean: true,
  esbuildOptions: {
    splitting: false,
    format: 'cjs',
    outExtension: {},
  },
});

Create a custom setup

You can use @esbuild-plugins/esm-externals with the following setup to fix this issue

build.mjs
import { EsmExternalsPlugin } from '@esbuild-plugins/esm-externals';
import { build } from 'esbuild-azure-functions';
import repl from 'repl';

await build({
  project: '.',
  esbuildOptions: {
    plugins: [EsmExternalsPlugin({ externals: [...repl._builtinLibs] })],
  },
});

If there are other modules causing issues for you, just add them to the externals options of EsmExternalsPlugin.

Sometimes, however, there are packages that want to patch require (like diagnostic-channel). In that case, you have to use config.enableRequireShim.

The import order of global imports is wrong

esbuild has a known issue (evanw/esbuild#399) with the code splitting feature and global imports. You can either turn off code splitting (see here) or make sure to import global imports everywhere you need them.

Last updated