Skip to content

Commit

Permalink
fix(javascript): fix CJS require importing .js
Browse files Browse the repository at this point in the history
  • Loading branch information
nbsp committed Nov 27, 2024
1 parent 24e8b6d commit 2d684e7
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/javascript/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,29 @@ const defaultOptions: Options = {
options.packages = 'external';
}
},
plugins: [
{
// https://github.com/egoist/tsup/issues/953#issuecomment-2294998890
// ensuring that all local requires/imports in `.cjs` files import from `.cjs` files.
// require('./path') → require('./path.cjs') in `.cjs` files
// require('../path') → require('../path.cjs') in `.cjs` files
// from './path' → from './path.cjs' in `.cjs` files
// from '../path' → from '../path.cjs' in `.cjs` files
name: 'fix-cjs-imports',
renderChunk(code) {
if (this.format === 'cjs') {
const regexCjs = /require\((?<quote>['"])(?<import>\.[^'"]+)\.js['"]\)/g;
const regexDynamic = /import\((?<quote>['"])(?<import>\.[^'"]+)\.js['"]\)/g;
const regexEsm = /from(?<space>[\s]*)(?<quote>['"])(?<import>\.[^'"]+)\.js['"]/g;
return {
code: code
.replace(regexCjs, 'require($<quote>$<import>.cjs$<quote>)')
.replace(regexDynamic, 'import($<quote>$<import>.cjs$<quote>)')
.replace(regexEsm, 'from$<space>$<quote>$<import>.cjs$<quote>'),
};
}
},
},
]
};
export default defaultOptions;

0 comments on commit 2d684e7

Please sign in to comment.