Optional chain is incorrectly removed when used on import
See original GitHub issueBug report
What is the current behavior?
Webpack incorrectly compiles x?.value
to (something).value
when x
is something that’s been imported.
If the current behavior is a bug, please provide the steps to reproduce.
webpack.config.js:
module.exports = {
entry: "./index.js",
target: "web",
};
index.js:
import x from './x.js';
console.log(`optional value is: ${x?.value}`);
x.js:
export default undefined;
Produces dist/main.js:
(()=>{"use strict";console.log(`optional value is: ${(void 0).value}`)})();
which leads to TypeError: Cannot read property 'value' of undefined
at runtime.
What is the expected behavior?
The ?
should be retained or converted to a ternary operator.
When import x from './x.js';
is removed and replaced with const x = (() => void console)();
(something complicated enough that webpack doesn’t completely constant-fold it), the output is:
(()=>{const o=void console;console.log(`optional value is: ${o?.value}`)})();
which is as expected (the ?
is retained).
Other relevant information: webpack version: latest, 5.27.2 Node.js version: v15.9.0 Operating System: macOS 11.2.2
Issue Analytics
- State:
- Created 2 years ago
- Reactions:29
- Comments:26 (10 by maintainers)
Top GitHub Comments
seems to be included in
5.71.0
now 🥳A simple workaround we’ve found is referencing the imported module as another variable. For example:
Not ideal, but it works until this can be fixed.