Skip to content

Commit a12ed0c

Browse files
committed
Skip optional dependencies in ESM externals
Fixes #10159
1 parent e6fe231 commit a12ed0c

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

packages/core/integration-tests/test/javascript.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6251,4 +6251,37 @@ describe('javascript', function () {
62516251
assert.equal(res.hashed, 'ae2b1fca515949e5d54fb22b8ed95575');
62526252
assert.equal(res.default, 'Test');
62536253
});
6254+
6255+
it('should not add ESM externals for optional requires', async () => {
6256+
await fsFixture(overlayFS, __dirname)`
6257+
esm-externals
6258+
index.js:
6259+
let test;
6260+
try {
6261+
require('optional');
6262+
test = 'fail';
6263+
} catch {
6264+
test = 'pass';
6265+
}
6266+
export default test;
6267+
6268+
package.json:
6269+
{
6270+
"targets": {
6271+
"default": {
6272+
"context": "node",
6273+
"outputFormat": "esmodule"
6274+
}
6275+
}
6276+
}
6277+
6278+
yarn.lock:`;
6279+
6280+
let b = await bundle(path.join(__dirname, 'esm-externals/index.js'), {
6281+
inputFS: overlayFS,
6282+
});
6283+
6284+
let res = await run(b);
6285+
assert.equal(res.default, 'pass');
6286+
});
62546287
});

packages/packagers/js/src/DevPackager.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,10 @@ export class DevPackager {
122122
} else {
123123
// An external module - map placeholder to original specifier.
124124
deps[specifier] = dep.specifier;
125-
if (this.bundle.env.outputFormat === 'esmodule') {
125+
if (
126+
this.bundle.env.outputFormat === 'esmodule' &&
127+
!dep.isOptional
128+
) {
126129
externals.add(dep.specifier);
127130
}
128131
}

0 commit comments

Comments
 (0)