question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Uncaught ReferenceError: require is not defined when <script type="module"....>

See original GitHub issue

🐛 bug report

An app with <script type="module"... /> its index.html is properly parsed and served by Chrome, but after being built with ParcelJS causes Uncaught ReferenceError: require is not defined. This however doesn’t make the app malfunctioning.

Configuration

package.json

{
  "name": "index",
  "version": "0.0.1",
  "description": "Test building ES6 app with ParcelJS",
  "main": "./src/index.html",
  "repository": "https://github.com/OleksiyRudenko/test-parcel-es6.git",
  "author": "Oleksiy Rudenko <oleksiy.rudenko@gmail.com>",
  "license": "MIT",
  "scripts": {
    "start": "parcel ./src/index.html --public-url ./",
    "watch": "parcel watch ./src/index.html --public-url ./",
    "build-dev": "parcel build ./src/index.html --no-minify --public-url ./",
    "build": "parcel build ./src/index.html --public-url ./"
  }
}

Expected Behavior

The app comprising features supported by a given browser and served raw to the browser producing no errors wouldn’t produce any errors being built with ParcelJS with basic settings.

😯 Current Behavior

The built app runs while browser reports Uncaught ReferenceError: require is not defined

I believe it happens since ES6 modules are strict-mode code and resulting JS bundle starts with require = (function (modules, cache, entry)... .

💁 Possible Solution

Replacing type='module' with e.g. defer in a <script> tag produces a fatal error (Uncaught SyntaxError: Unexpected identifier) at the very first import....

My qualifications are insufficient to suggest any workarounds. I am sorry about that. Would appreciate any advice to overcome the issue.

🔦 Context

Building an application while enjoying ES6 modules.

💻 Code Sample

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test ES6 build with ParcelJS</title>
    <script type="module" src="./index.js"></script>
</head>
<body>
    <h2>See dev console</h2>
</body>
</html>

index.js

import App from './App.js';
new App();

App.js

export default class App {
  constructor() {
    console.log('App instance created.')
  }
}

The above is to illustrate some sensible code. Building the app with empty index.js (and therefore ineffective App.js) still results in Uncaught ReferenceError: require is not defined.

The produced JS bundle reads:

// modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles

// eslint-disable-next-line no-global-assign
require = (function (modules, cache, entry) {
  // Save the require from previous bundle to this closure if any
  var previousRequire = typeof require === "function" && require;

  function newRequire(name, jumped) {
    if (!cache[name]) {
      if (!modules[name]) {
        // if we cannot find the module within our internal map or
        // cache jump to the current global require ie. the last bundle
        // that was added to the page.
        var currentRequire = typeof require === "function" && require;
        if (!jumped && currentRequire) {
          return currentRequire(name, true);
        }

        // If there are other bundles on this page the require from the
        // previous one is saved to 'previousRequire'. Repeat this as
        // many times as there are bundles until the module is found or
        // we exhaust the require chain.
        if (previousRequire) {
          return previousRequire(name, true);
        }

        var err = new Error('Cannot find module \'' + name + '\'');
        err.code = 'MODULE_NOT_FOUND';
        throw err;
      }

      localRequire.resolve = resolve;

      var module = cache[name] = new newRequire.Module(name);

      modules[name][0].call(module.exports, localRequire, module, module.exports);
    }

    return cache[name].exports;

    function localRequire(x){
      return newRequire(localRequire.resolve(x));
    }

    function resolve(x){
      return modules[name][1][x] || x;
    }
  }

  function Module(moduleName) {
    this.id = moduleName;
    this.bundle = newRequire;
    this.exports = {};
  }

  newRequire.isParcelRequire = true;
  newRequire.Module = Module;
  newRequire.modules = modules;
  newRequire.cache = cache;
  newRequire.parent = previousRequire;

  for (var i = 0; i < entry.length; i++) {
    newRequire(entry[i]);
  }

  // Override the current require with this new one
  return newRequire;
})({2:[function(require,module,exports) {
},{}]},{},[2])

🌍 Your Environment

Software Version(s)
Parcel 1.6.2
Node 8.9.4.
Yarn 1.3.2
Operating System MS Windows 8.1 / 10
Browser Version 63.0.3239.132 (Official Build) (64-bit)

Similar behaviour under both Windows flavours.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:8
  • Comments:10 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
alexeyraspopovcommented, Mar 25, 2019

This issue was obviously opened earlier than #1401 which means that #1401 is a duplicate.

1reaction
dfkayecommented, Sep 25, 2018

temporary fix for your work environment or localhost - https://twitter.com/dfkaye/status/1044693110700171264

Read more comments on GitHub >

github_iconTop Results From Across the Web

Client on Node.js: Uncaught ReferenceError: require is not ...
throws the Uncaught ReferenceError: require is not defined ... include the main JavaScript file using attribute type="module" (browser support): <script ...
Read more >
ReferenceError: require is not defined in JavaScript - Stack Diary
Node.js. One way to fix this error is to ensure that your code is being executed in a Node.js environment. node my-script.js.
Read more >
How to fix "require is not defined" in JavaScript / Node.js?
It is not uncommon to run into errors like “ReferenceError: require is not defined” when learning how to code or develop projects.
Read more >
How To Fix ReferenceError require is not defined in JavaScript
You tried using require in a browser environment; You are in a Node.js environment but your project has "type": "module" in its package.json....
Read more >
Javascript - How to fix ReferenceError: require is not defined
Learn how you can fix JavaScript ReferenceError: require is not defined. Browser and Node.js environment.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found