From 1a8d3f01ef67f6ce2bbecf552bc09fca5b0b8250 Mon Sep 17 00:00:00 2001 From: achingbrain Date: Tue, 23 Nov 2021 11:28:09 +0000 Subject: [PATCH] fix: add .js extension to imports and fix package.json This fixes two problems with the ESM build of this module. 1. The `package.json` that contains `{ "type": "module" }` wasn't being included in the npm tarball 2. When running in an ESM environment, `import foo from './bar'` does not work, you have to specify the extension The fix for the first is simple, add the cjs/esm `package.json` files to the `files` array in the project `package.json`. The second fix is harder. If you just add the `.js` extension to the source files, typescript is happy but ts-node is not, and this project uses ts-node to run the tests without a compile step. Typescript does not support importing `*.ts` and will not support adding `*.js` to the transpiled output - https://github.com/microsoft/TypeScript/issues/16577 ts-node thought this was a bug in Typescript but it turns out not. Their suggestion to use `ts-node/esm` breaks sourcemap support because `source-map-support/register` is not esm - https://github.com/TypeStrong/ts-node/issues/783 There is a PR against ts-node to add support for resolving `./foo.js` if `./foo.ts` or `./foo` fails but it seems to have stalled - https://github.com/TypeStrong/ts-node/pull/1361 Given all of the above, the most expedient way forward seemed to just be to add a shell script that rewrites the various `import` statements in the esm output to add the `.js` extension, then if the ts-node PR ever gets merged the script can be backed out. Fixes #147 --- .fix-esm-imports.sh | 4 ++++ package.json | 5 +++-- 2 files changed, 7 insertions(+), 2 deletions(-) create mode 100755 .fix-esm-imports.sh diff --git a/.fix-esm-imports.sh b/.fix-esm-imports.sh new file mode 100755 index 0000000..7e4df1e --- /dev/null +++ b/.fix-esm-imports.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +# Search for "from './baz'" and transform to "from './baz.js'" +find dist/esm -type f -name *.js -exec sed -i -e -E "s/from '(\.\/.*)'/from '\1.js'/g" {} \; \ No newline at end of file diff --git a/package.json b/package.json index 1534c2e..57ba940 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ }, "scripts": { "docs": "documentation build --github --output docs --format html ./ip-address.js", - "build": "rm -rf dist/* && tsc -p tsconfig.json && tsc -p tsconfig-esm.json && ./.fix-package-types.sh", + "build": "rm -rf dist/* && tsc -p tsconfig.json && tsc -p tsconfig-esm.json && ./.fix-package-types.sh && ./.fix-esm-imports.sh", "prepublishOnly": "npm run build", "release": "release-it", "test-ci": "nyc mocha", @@ -53,7 +53,8 @@ "files": [ "dist/**/*.js", "dist/**/*.ts", - "dist/**/*.map" + "dist/**/*.map", + "dist/**/*.json" ], "repository": { "type": "git",