From 7fd96b5db2bc963baaef56f2e1d3b9b6eb6f775f Mon Sep 17 00:00:00 2001 From: Julien Poissonnier Date: Fri, 10 Jan 2025 20:43:41 +0100 Subject: [PATCH] Add docs on how to use native ESM with Node.js Provide official documentation on how to natively use ESM instead of compiling to CommonJS. --- .../iac/languages-sdks/javascript/_index.md | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/content/docs/iac/languages-sdks/javascript/_index.md b/content/docs/iac/languages-sdks/javascript/_index.md index 37bb7a43f734..b3b1ead2523c 100644 --- a/content/docs/iac/languages-sdks/javascript/_index.md +++ b/content/docs/iac/languages-sdks/javascript/_index.md @@ -208,6 +208,49 @@ runtime: typescript: false ``` +## Native ESM Support + +The default Pulumi templates compile TypeScript code to [CommonJS](https://nodejs.org/api/modules.html) modules. You can use ESM syntax like `import` or `export` in your code, but it will be compiled to CommonJS behind the scenes. + +If you wish to instead use [ESM](https://nodejs.org/api/esm.html) natively, you can set the `type` field in your `package.json` to `module`. This will tell Node.js to treat your package as an ESM package. + +```json +{ + "name": "my-package", + "version": "1.0.0", + "type": "module", + ... +} +``` + +Your `tsconfig.json` file should also be updated to ensure that TypeScript outputs ESM, by setting the [`module`](https://www.typescriptlang.org/tsconfig/#module) field to `ESNext`, or one of `ES2015/ES6/ES2020/ES2022`. + +```json +{ + "compilerOptions": { + ... + "module": "ESNext", + ... + } +} +``` + +Install a recent version of `ts-node` to use its [ESM loader](https://typestrong.org/ts-node/docs/imports#native-ecmascript-modules). + +```bash +npm install ts-node@^10 +``` + +Lastly, you need to instruct Pulumi to use the ts-node/ESM loader by setting the `nodeargs` option in the [`runtime`](https://www.pulumi.com/docs/iac/concepts/projects/project-file/#runtime-options) options in `Pulumi.yaml`. + +```yaml +name: project-using-native-esm +runtime: + name: nodejs + options: + nodeargs: "--loader ts-node/esm --no-warnings" +``` + ## Package Management Pulumi has official support for NPM and Yarn Classic. Pulumi does