Parcel does not transform require.cache when bundling, which cause an error when running the bundled file.
// in package.json
"esm": "dist/index.js",
"targets": {
"esm": {
"includeNodeModules": true,
"outputFormat": "esmodule",
"isLibrary": true
}
},
The bundle command is parcel build index.js --target esm --no-minify
The bundled output should run without error.
Running the bundled file will cause the following error:
file:///<path>/parcel-repro/dist/index.js:4
for (const file in require.cache) {
^
ReferenceError: require is not defined
at file:///<path>/parcel-repro/dist/index.js:4:28
at ModuleJob.run (internal/modules/esm/module_job.js:110:37)
at async Loader.import (internal/modules/esm/loader.js:179:24)
Parcel 1 created a shim for require.cache. See this earlier issue and PR:
In the v2 branch there is a skipped test for the shim.
I want to package node_modules dependencies into my bundle. Some of these dependencies make use of require.cache.
Repro here: https://github.com/m-allanson/parcel-require-repro
The dist directory is committed too.
Example code that will cause the error:
// in src file index.js
for (const file in require.cache) {
if (/color/g.test(file)) {
result[file] = true;
}
}
| Software | Version(s) |
| ---------------- | ---------- |
| Parcel | 2.0.0-alpha.3.2
| Node | 12 or 14 (for ESM support)
| npm/Yarn | npm
| Operating System | macOS
A quick trial shows this working for me ๐ It reinstates the parcel v1 shim behaviour. Is there somewhere I can add tests?
if (t.matchesPattern(path.node, 'module.id')) {
path.replaceWith(t.stringLiteral(asset.id));
}
if (t.matchesPattern(path.node, 'module.hot')) {
path.replaceWith(t.identifier('null'));
}
if (t.matchesPattern(path.node, 'module.require') && !asset.env.isNode()) {
path.replaceWith(t.identifier('null'));
}
+ if (t.matchesPattern(path.node, 'require.cache') && !asset.env.isNode()) {
+ path.replaceWith(t.identifier('{}'));
+ }
if (t.matchesPattern(path.node, 'module.bundle')) {
path.replaceWith(t.identifier('parcelRequire'));
}
The fixture would be similar to https://github.com/parcel-bundler/parcel/tree/v2/packages/core/integration-tests/test/integration/scope-hoisting/commonjs/require-resolve (also in the commonjs folder) and the test itself in https://github.com/parcel-bundler/parcel/blob/v2/packages/core/integration-tests/test/scope-hoisting.js.
Great, thank you! I aim to open a PR this week.
This issue should be closed fixed by #4621
@navaru it did not get fixed, the PR has been closed not merged.