From 0d5a9839c14ed4b6dd8cd983c81a887c9dcc0e1d Mon Sep 17 00:00:00 2001 From: aoife cassidy Date: Wed, 27 Nov 2024 19:51:48 +0200 Subject: [PATCH] fix(javascript): fix CJS require importing .js (#897) --- .changeset/few-dolls-exercise.md | 5 +++++ packages/javascript/tsup.config.ts | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 .changeset/few-dolls-exercise.md diff --git a/.changeset/few-dolls-exercise.md b/.changeset/few-dolls-exercise.md new file mode 100644 index 00000000..85445ec3 --- /dev/null +++ b/.changeset/few-dolls-exercise.md @@ -0,0 +1,5 @@ +--- +"@livekit/protocol": patch +--- + +fix CJS require importing .js diff --git a/packages/javascript/tsup.config.ts b/packages/javascript/tsup.config.ts index 01533005..e13e726c 100644 --- a/packages/javascript/tsup.config.ts +++ b/packages/javascript/tsup.config.ts @@ -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\((?['"])(?\.[^'"]+)\.js['"]\)/g; + const regexDynamic = /import\((?['"])(?\.[^'"]+)\.js['"]\)/g; + const regexEsm = /from(?[\s]*)(?['"])(?\.[^'"]+)\.js['"]/g; + return { + code: code + .replace(regexCjs, 'require($$.cjs$)') + .replace(regexDynamic, 'import($$.cjs$)') + .replace(regexEsm, 'from$$$.cjs$'), + }; + } + }, + }, + ] }; export default defaultOptions;