Parcel: Require.cache causes errors

Created on 16 May 2020  ยท  6Comments  ยท  Source: parcel-bundler/parcel

๐Ÿ› bug report

Parcel does not transform require.cache when bundling, which cause an error when running the bundled file.

๐ŸŽ› Configuration (.babelrc, package.json, cli command)

// 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

๐Ÿค” Expected Behavior

The bundled output should run without error.

๐Ÿ˜ฏ Current Behavior

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)

๐Ÿ’ Possible Solution

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.

๐Ÿ”ฆ Context

I want to package node_modules dependencies into my bundle. Some of these dependencies make use of require.cache.

๐Ÿ’ป Code Sample

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;
  }
}

๐ŸŒ Your Environment

| Software | Version(s) |
| ---------------- | ---------- |
| Parcel | 2.0.0-alpha.3.2
| Node | 12 or 14 (for ESM support)
| npm/Yarn | npm
| Operating System | macOS

Good First Issue Bug Help Wanted โœจ Parcel 2 ๐ŸŒณ Tree Shaking

All 6 comments

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')); 
     } 

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.

Was this page helpful?
0 / 5 - 0 ratings