Skip to content

Commit

Permalink
feat: build cjs modules
Browse files Browse the repository at this point in the history
  • Loading branch information
gjbkz committed Aug 31, 2023
1 parent 3bcbce2 commit 1b3dac4
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@
"repository": "https://github.com/nlibjs/typing",
"type": "module",
"main": "./esm/index.mjs",
"exports": {
"import": "./esm/index.mjs",
"require": "./cjs/index.cjs"
},
"files": [
"cjs",
"esm",
"!**/*.test.*"
],
Expand All @@ -26,6 +31,9 @@
"build": "run-s build:*",
"build:index": "npx @nlib/indexen --output src/index.mts \"./**/*.mts\"",
"build:esm": "tsc",
"build:cjs": "run-s build:cjs:*",
"build:cjs:tsc": "tsc --project tsconfig.cjs.json",
"build:cjs:rename": "node rename-cjs.mjs",
"version": "npx @nlib/changelog --output CHANGELOG.md && git add CHANGELOG.md"
},
"devDependencies": {
Expand Down
42 changes: 42 additions & 0 deletions rename-cjs.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/* eslint-env es6 */
//@ts-check
import * as fs from 'node:fs/promises';
import { URL } from 'node:url';
import * as console from 'node:console';

/**
* @param {URL} file
* @returns {AsyncGenerator<URL>}
*/
export const listFiles = async function* (file) {
const stats = await fs.stat(file);
if (stats.isFile()) {
yield file;
return;
}
if (stats.isDirectory()) {
file.pathname = file.pathname.replace(/\/*$/, '/');
for (const name of await fs.readdir(file)) {
yield* listFiles(new URL(name, file));
}
}
};

/** @type {Array<[URL, URL]>} */
const renames = [];
const cjsDir = new URL('cjs/', import.meta.url);
for await (const file of listFiles(cjsDir)) {
if (/\.m[jt]s$/.test(file.pathname)) {
const renamed = new URL(file.href);
renamed.pathname = renamed.pathname.replace(/\.m([jt])s$/, '.c$1s');
renames.push([file, renamed]);
}
}
await Promise.all(
renames.map(async ([from, to]) => {
let code = await fs.readFile(from, 'utf8');
code = code.replace(/\.m([jt])s(['"])/g, '.c$1s$2');
await fs.writeFile(to, code);
console.info('renamed', to.pathname.slice(cjsDir.pathname.length));
}),
);
9 changes: 9 additions & 0 deletions tsconfig.cjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"moduleResolution": "Node",
"outDir": "cjs"
}
}

0 comments on commit 1b3dac4

Please sign in to comment.