Skip to content

Commit

Permalink
Add cjs support (h/t @acheronfail in flightcontrolhq#301)
Browse files Browse the repository at this point in the history
  • Loading branch information
half0wl committed Nov 29, 2024
1 parent 0130a80 commit a42fb31
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 5 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
dist
dist-cjs
coverage
29 changes: 29 additions & 0 deletions commonjs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import fs from 'fs';
import path from 'path';

function convertToCommonJs(filePath) {
// update imports
const content = fs.readFileSync(filePath, 'utf-8');
const updatedContent = content.replace(
/(require\(['"])(.*)(\.js)(['"]\))/g,
'$1$2.cjs$4'
);
fs.writeFileSync(filePath, updatedContent, 'utf-8');

// update file extension
const commonJsPath = filePath.replace(/\.js$/, '.cjs');
fs.renameSync(filePath, commonJsPath);
}

function walk(dir) {
fs.readdirSync(dir).forEach((file) => {
const fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
walk(fullPath);
} else if (file.endsWith('.js')) {
convertToCommonJs(fullPath);
}
});
}

walk('./dist-cjs');
15 changes: 10 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,20 @@
"typings": "dist/index.d.ts",
"main": "./dist/index.js",
"exports": {
".": "./dist/index.js"
"import": "./dist/index.js",
"require": "./dist-cjs/index.cjs"
},
"files": [
"dist"
"dist",
"dist-cjs"
],
"engines": {
"node": ">=16"
},
"scripts": {
"build": "tsc",
"build": "yarn run build:esm && yarn run build:cjs",
"build:esm": "tsc -p tsconfig.json",
"build:cjs": "tsc -p tsconfig.cjs.json && node commonjs.js",
"test": "vitest run",
"lint": "tsdx lint",
"prepack": "yarn build",
Expand All @@ -33,7 +37,8 @@
"singleQuote": true,
"trailingComma": "es5"
},
"name": "superjson",
"name": "@half0wl/superjson",
"description": "fork of superjson with cjs support",
"author": {
"name": "Simon Knott",
"email": "[email protected]",
Expand All @@ -53,7 +58,7 @@
],
"repository": {
"type": "git",
"url": "https://github.com/blitz-js/superjson"
"url": "https://github.com/half0wl/superjson-cjs"
},
"devDependencies": {
"@types/debug": "^4.1.5",
Expand Down
7 changes: 7 additions & 0 deletions tsconfig.cjs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"outDir": "dist-cjs"
}
}

0 comments on commit a42fb31

Please sign in to comment.