Skip to content

Commit

Permalink
chore(esm-post-process): import extensions for files only, .d.ts supp…
Browse files Browse the repository at this point in the history
…ort and cleanup
  • Loading branch information
enisdenjo committed Sep 12, 2022
1 parent 842d0de commit 3dc6f33
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 21 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@
"test": "jest",
"bench:start-servers": "NODE_ENV=production node benchmark/servers/index.mjs",
"bench": "k6 run benchmark/k6.mjs",
"build:esm": "tsc -b tsconfig.esm.json && node scripts/esm-post-process.js",
"build:esm": "tsc -b tsconfig.esm.json && node scripts/esm-post-process.mjs",
"build:cjs": "tsc -b tsconfig.cjs.json",
"build:umd": "rollup -c && gzip umd/graphql-ws.min.js -c > umd/graphql-ws.min.js.gz",
"build": "yarn build:esm && yarn build:cjs && yarn build:umd",
Expand Down
20 changes: 0 additions & 20 deletions scripts/esm-post-process.js

This file was deleted.

66 changes: 66 additions & 0 deletions scripts/esm-post-process.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// @ts-check

import fs from 'fs/promises';
import path from 'path';
import glob from 'glob';

const rootDir = 'lib';

glob(`${rootDir}/**/*.js`, async (_, matches) => {
for (const path of matches) {
await buildEsm(path);
}

// we delete after build to not mess with import/export statement replacer
for (const path of matches) {
await fs.unlink(path);
}
});

glob(`${rootDir}/**/*.d.ts`, async (_, matches) => {
for (const path of matches) {
await buildEsm(path);
}

// we dont delete raw d.ts files, they're still needed for imports/exports
});

/**
* @param {string} filePath
*/
async function buildEsm(filePath) {
const pathParts = filePath.split('.');
const fileExt = pathParts.pop();

const file = await fs.readFile(path.join(process.cwd(), filePath));
let content = file.toString();

if (fileExt === 'js') {
// add .mjs to all import/export statements, but only on files (keep directory imports as is)
for (const match of content.matchAll(/from '(\.?\.\/[^']*)'/g)) {
const [statement, relImportPath] = match;
const absImportPath = path.resolve(
process.cwd(),
path.dirname(filePath),
relImportPath,
);

try {
await fs.stat(absImportPath + '.js');

// file import
content = content.replace(statement, `from '${relImportPath}.mjs'`);
} catch {
// directory import
content = content.replace(
statement,
`from '${relImportPath}/index.mjs'`,
);
}
}
}

// write to file with prepended "m" in extension (.js -> .mjs, .ts -> .mts)
const esmFilePath = pathParts.join('.') + '.m' + fileExt;
await fs.writeFile(esmFilePath, content);
}

0 comments on commit 3dc6f33

Please sign in to comment.