-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Description
Bug report
What is the current behavior?
When using commonjs-static as the library type along with ts-loader, webpack may output a bundle that is syntactically invalid. In particular, if the keyword this is present in the source code at the module level (as it may be in e.g. code transpiled from TypeScript, or in polyfill code), webpack ends up generating a for loop which is missing a closing brace:
/******/ var __webpack_exports__ = {};
/******/ __webpack_modules__["./src/index.ts"](0, __webpack_exports__);
/******/ for(var __webpack_i__ in __webpack_exports__) {
/******/ exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
/******/
/******/ Object.defineProperty(exports, "__esModule", { value: true });> npx webpack build
asset main.js 1.67 KiB [emitted] (name: main)
./src/index.ts 194 bytes [built] [code generated]
webpack 5.99.8 compiled successfully in 686 ms
> node dist/main.js
./dist/main.js:36
/******/ })()
^
SyntaxError: Unexpected token ')'
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1176:20)
at Module._compile (node:internal/modules/cjs/loader:1218:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
Node.js v18.16.0
If the current behavior is a bug, please provide the steps to reproduce.
- Create a project from the files in this gist (put
index.tsinsrc): https://gist.github.com/arvidfm/350eb8bdb328b0e70fec2eeea240a6df - Run
npx webpack build - Run
node dist/main.js
What is the expected behavior?
node dist/main.js should execute successfully, without raising a SyntaxError.
Other relevant information:
The issue can be found on these lines:
webpack/lib/library/AssignLibraryPlugin.js
Lines 339 to 349 in a113022
| result.add(`for(var __webpack_i__ in ${exports}) {\n`); | |
| const hasProvided = provided.length > 0; | |
| if (hasProvided) { | |
| result.add( | |
| ` if (${JSON.stringify(provided)}.indexOf(__webpack_i__) === -1) {\n` | |
| ); | |
| } | |
| result.add( | |
| ` ${hasProvided ? " " : ""}${webpackExportTarget}[__webpack_i__] = ${exports}[__webpack_i__];\n` | |
| ); | |
| result.add(hasProvided ? " }\n}\n" : "\n"); |
In particular, if hasProvided is false, the closing brace for the for loop is not emitted.
> npx webpack --version
System:
OS: Linux 6.11 Ubuntu 24.04.2 LTS 24.04.2 LTS (Noble Numbat)
CPU: (20) x64 12th Gen Intel(R) Core(TM) i7-12800H
Memory: 13.76 GB / 30.98 GB
Binaries:
Node: 18.16.0 - ~/.nix-profile/bin/node
npm: 9.5.1 - ~/.nix-profile/bin/npm
Packages:
ts-loader: 9.5.2 => 9.5.2
webpack: 5.99.8 => 5.99.8
webpack-cli: 6.0.1 => 6.0.1