diff --git a/.gitignore b/.gitignore index 0e75fe5..a2f9a25 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules dist +dist-cjs coverage diff --git a/commonjs.js b/commonjs.js new file mode 100644 index 0000000..7bf5e61 --- /dev/null +++ b/commonjs.js @@ -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'); diff --git a/package.json b/package.json index bf2c71e..8b421a8 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json new file mode 100644 index 0000000..67774df --- /dev/null +++ b/tsconfig.cjs.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "CommonJS", + "outDir": "dist-cjs" + } +}