Skip to content

Commit

Permalink
Add docs on how to use native ESM with Node.js
Browse files Browse the repository at this point in the history
Provide official documentation on how to natively use ESM instead of compiling to CommonJS.
  • Loading branch information
julienp committed Jan 10, 2025
1 parent 3775cb7 commit 7fd96b5
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions content/docs/iac/languages-sdks/javascript/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 7fd96b5

Please sign in to comment.