diff --git a/src/build-commonjs.ts b/src/build-commonjs.ts index d823a61..c23436b 100644 --- a/src/build-commonjs.ts +++ b/src/build-commonjs.ts @@ -1,6 +1,6 @@ import chalk from 'chalk' import { spawnSync } from 'node:child_process' -import { renameSync, unlinkSync } from 'node:fs' +import { existsSync, renameSync, unlinkSync } from 'node:fs' import { relative, resolve } from 'node:path/posix' import buildFail from './build-fail.js' import config from './config.js' @@ -10,6 +10,10 @@ import setFolderDialect from './set-folder-dialect.js' import './tsconfig.js' const { commonjsDialects = [] } = config +const unlinkIfExist = (f: string) => existsSync(f) && unlinkSync(f) +const renameIfExist = (f: string, to: string) => + existsSync(f) && renameSync(f, to) + export const buildCommonJS = () => { setFolderDialect('src', 'commonjs') for (const d of ['commonjs', ...commonjsDialects]) { @@ -33,10 +37,12 @@ export const buildCommonJS = () => { `.tshy-build/${d}`, relative(resolve('src'), resolve(orig)) ).replace(/\.tsx?$/, '') - unlinkSync(`${stemTo}.js.map`) - unlinkSync(`${stemTo}.d.ts.map`) - renameSync(`${stemFrom}.cjs`, `${stemTo}.js`) - renameSync(`${stemFrom}.d.cts`, `${stemTo}.d.ts`) + const stemToPath = `${stemTo}.js.map` + const stemToDtsPath = `${stemTo}.d.ts.map` + unlinkIfExist(stemToPath) + unlinkIfExist(stemToDtsPath) + renameIfExist(`${stemFrom}.cjs`, `${stemTo}.js`) + renameIfExist(`${stemFrom}.d.cts`, `${stemTo}.d.ts`) } console.error(chalk.cyan.bold('built commonjs')) }