Skip to content

Commit

Permalink
fix: support cjs
Browse files Browse the repository at this point in the history
  • Loading branch information
acheronfail committed Oct 8, 2024
1 parent 0130a80 commit 607e986
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 3 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
26 changes: 26 additions & 0 deletions commonjs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
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');
10 changes: 7 additions & 3 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 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 607e986

Please sign in to comment.