From 788ceaf4a3e588f7e32cb724f76519a8eeaaf217 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Tue, 25 Oct 2022 08:00:22 +0100 Subject: [PATCH] docs: add ts section to esm upgrade guide Improve docs around upgrading ts projects to use esm. --- docs/upgrading/v0.62-v0.63.md | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/docs/upgrading/v0.62-v0.63.md b/docs/upgrading/v0.62-v0.63.md index 14505b2e26..9c9910891b 100644 --- a/docs/upgrading/v0.62-v0.63.md +++ b/docs/upgrading/v0.62-v0.63.md @@ -6,6 +6,7 @@ ## Table of Contents - [ESM](#esm) + - [TypeScript and ESM](#typescript-and-esm) - [`libp2p@0.37.x`](#libp2p037x) - [PeerIds](#peerids) - [multiaddrs](#multiaddrs) @@ -34,6 +35,48 @@ async function loadIpfs () { } ``` +### TypeScript and ESM + +When authoring typescript it can often look like you are writing ESM: + +```ts +import { create } from 'ipfs-core' + +create() +``` + +When this is transpiled to JavaScript the default settings will emit CJS which will fail at runtime: + +```js +"use strict"; +exports.__esModule = true; +var ipfs_core_1 = require("ipfs-core"); +(0, ipfs_core_1.create)(); +``` + +You may also see errors about private identifiers: + +```console +node_modules/@libp2p/interfaces/dist/src/events.d.ts:19:5 - error TS18028: Private identifiers are only available when targeting ECMAScript 2015 and higher. + +19 #private; + ~~~~~~~~ +``` + +To build correctly with ESM as a target, update your `tsconfig.json` to include the following: + +```js +{ + "module": "es2020", // ensures output is ESM + "target": "es2020", // support modern features like private identifiers + // other settings +} +``` + +They must both be set to `es2020` at least, more recent versions will also work. + +If in doubt, examine the JavaScript files `tsc` emits and ensure that any `ipfs` modules are being loaded with `import` and not `require`. + ## `libp2p@0.37.x` `ipfs@0.63.x` upgrades to `libp2p@0.37.x`. This is a significant refactor that ports the entire stack to TypeScript and publishes all modules as ESM-only code.