Using ECMAScript modules (ESM)
Using native ECMAScript modules is the official way of developing JavaScript software today. More and more projects and libraries are adopting this as industry standard.
Since support for CommonJS is declining, we recommend you to move away from it.
Migrating to ESM
The recommended way to use ESM in Node.js, is by adding "type": "module"
to your package.json
. This makes it the default for your entire project:
{
"type": "module"
}
Make sure to also configure your Lambda Node.js CDK Construct accordingly:
new NodejsFunction(this, id, {
bundling: {
format: OutputFormat.ESM,
// ...
// enable if you find any issues with CommonJS modules that need "require()"
//banner: "import { createRequire } from 'module';const require = createRequire(import.meta.url);",
},
});
TypeScript
In TypeScript, make sure to have "module": "preserve"
in your tsconfig.json
. This is because we're transpiling with AWS CDK which uses esbuild under the hood.
TIP
You can also use @backpack/typescript-config
which contains presets for your TSConfig.
Read more on best practices for TypeScript.
Switch from Jest to Vitest (recommended)
Jest has experimental support for ESM, which requires a lot of additional configuration. Therefore, we recommend to use Vitest instead, which supports ESM out of the box.
Please read more about our recommended tooling.