parcel-bundler/parcel

Require.cache causes errors

Open

#4616 opened on May 16, 2020

View on GitHub
 (6 comments) (0 reactions) (0 assignees)JavaScript (44,030 stars) (2,274 forks)batch import
:bug: Bug:pray: Help WantedGood First Issue✨ Parcel 2🌳 Scope Hoisting

Description

🐛 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

Contributor guide