Parcel React component library throws an error stating that "require is not defined

Error message:

Uncaught ReferenceError: require is not defined
    at index.js?5WdmUIncGTkIrWhONvlEDQ:1:1
(anonymous) @ index.js?5WdmUIncGTkIrWhONvlEDQ:1

First lines of index.js:

require("./index.css");
var $cI6W1$lodash = require("lodash");
var $cI6W1$react = require("react");
var $cI6W1$reactdom = require("react-dom");
var $cI6W1$swchelperslib_define_propertyjs = require("@swc/helpers/lib/_define_property.js");
var $cI6W1$chrononode = require("chrono-node");

Here is my package.json file:

{
  "name": "stacks-components",
  "version": "1.0.0",
  "description": "Components for Stacks CMS",
  "private": true,
  "main": "../public/js/index.js",
  "browserslist": "> 0.5%, last 2 versions, not dead",
  "scripts": {
    "start": "parcel start app/index.jsx --host localhost --public-url /js",
    "build": "parcel build app/index.jsx --public-url /js"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@parcel/transformer-sass": "^2.8.3",
    "babel-eslint": "^10.0.3",
    "eslint": "^5.16.0",
    "eslint-plugin-react": "^7.17.0",
    "postcss": "^8.4.21",
    "postcss-modules": "^4.3.1"
  },
  "dependencies": {
    "@babel/core": "^7.7.7",
    "@babel/plugin-proposal-class-properties": "^7.7.4",
    "@babel/preset-react": "^7.7.4",
    "@draft-js-plugins/editor": "^4.1.0",
    "@swc/helpers": "^0.4.14",
    "autoprefixer": "^9.7.3",
    "chrono-node": "^2.3.8",
    "classnames": "^2.2.6",
    "dompurify": "^2.3.0",
    "draft-js": "^0.11.7",
    "draft-js-export-html": "^1.4.1",
    "draft-js-plugins-editor": "^3.0.0",
    "draggable": "^4.2.0",
    "dropzone": "^5.7.2",
    "linkify-html": "^3.0.5",
    "lodash": "^4.17.15",
    "openai": "^3.1.0",
    "parcel": "^2.8.3",
    "parcel-bundler": "^1.12.5",
    "react": "^16.13.1",
    "react-datetime-picker": "^3.0.4",
    "react-dom": "^16.12.0",
    "react-dropzone": "^11.2.0",
    "react-fetch-component": "^7.0.1",
    "react-router-dom": "^5.1.2",
    "react-select": "^3.1.0",
    "react-sortablejs": "^2.0.11",
    "ress": "^2.0.3",
    "rimraf": "^2.7.1",
    "sass": "^1.24.4",
    "trix": "^1.2.3",
    "uuid": "^8.3.1"
  },
  "_id": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b080f1a181008561814160b14151e150f083b4a554b554b">[email protected]</a>"
}

a sample of app/index.jsx

import _ from "lodash";
import React from "react";
import { render } from "react-dom";
import DateRange from "./components/DateRange";
import DraftJS from "./components/DraftJS";
import Supertag from "./components/Supertag";
// ...


// Use this file to mount all the components defined in the components folder

Dropzone.autoDiscover = false;

function dateRangeInit() {
  document.querySelectorAll(".date-range-react").forEach((element) => {
    render(
      React.createElement(DateRange, {
        fromVal: element.dataset.fromval,
        fromFieldName: element.dataset.fromfieldname,
        fromLabel: element.dataset.fromlabel,
        toVal: element.dataset.toval,
        toFieldName: element.dataset.tofieldname,
        toLabel: element.dataset.tolabel,
        recordType: element.dataset.recordtype,
      }),
      element
    );
  });
}

dateRangeInit();
...

I am able to successfully build, and I can confirm that the JS and CSS files are being generated in the proper location. But the "require" error appears in the browser when I try to load the page.

I am seeing this error as I attempt to upgrade from Parcel 1 to 2. This error was not happening in Parcel 1.

My use case is that I have a Ruby on Rails web app, but I use Parcel to build some ReactJS components. The index.js and index.css file is loaded on each page in the Rails app.

Answer №1

To ensure compatibility with my setup, I had to adjust the outputFormat setting to global in order for it to function as a "classic" script. For further details on the global format, refer to this documentation page.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simple way to extract the values from every input element within a specific <tr> tag using JQuery

Is there a way to align all input elements in a single row within my form? For example, consider the snippet of code provided below, which includes a checkbox and a text input box. I would like to retrieve the values from both of these input types and pres ...

In a Next.js application directory, how can you retrieve the router.asPath value within a function that utilizes the Next.js navigation feature?

import { useRoute } from "next/navigation" const route = useRoute() const updateData = () => { route.replace(route.asPath); } I attempted using next/router but it was unsuccessful ...

Importing images with relative paths from a JSON file does not work as expected in Next.js

JSON file data portion: { "categories": [ { "id": 1, "category_slug": "food_supplements", "title": "Food Supplements", "image": "/../../public/images/foodSupplements.png", } ] } Component data portion that displays the ...

Activate the search feature in select2 to allow multiple selections

I'm looking for a way to incorporate a search box into my multi-select fields using select2. Oddly enough, while the search boxes show up as expected in single-select fields, applying the same select2() function to a multi-select field doesn't s ...

Restricting the number of times a user can click on

I am currently displaying a table with data obtained from a database query. The structure of the table is outlined below: <table id="dt-inventory-list" class="table table-responsive"> <thead> <tr> <th>Field ...

Vue-based bot for telegram web application

Hey there, I've been working on integrating a web app with my chat bot, taking advantage of the new Telegram feature. Unfortunately, after adding the site, I'm encountering an issue where clicking the button opens up an empty page. It seems that ...

Encountered an error message stating "This dependency was not found" after installing a package using npm

I recently added a package called htmldiff to my Vue project using the npm install command. The next step was to try importing the package into one of my components. import { diff } from 'htmldiff'; // note that the package does not use default ...

Exploring the use of properties in JavaScript

I recently began learning Vue.js 2, but I encountered an issue when passing props to a child component. Here's the code snippet where I pass the prop: <div class="user"> <h3>{{ user.name }}</h3> <depenses :user-id="user.id"&g ...

What is the best method for sending form data, specifically uploaded images, in Python Bottle with Ajax?

This form belongs to me <form method='post' enctype='multipart/form-data' id='uploadForm' name='formn'> <input type='file' value='' name='newfile'> <input type=&a ...

Identifying text within clicked divs using identical ids

$(document).ready(function(){ $('#peoplelayer').click(function(){ $(this).fadeOut(500); var str = $(this).text(); alert(str); }); }); This is code where I use the same id "#peoplelayer" for all the divs. When on ...

HTML script tag failing to load

As a beginner in using scripts in HTML, I'm currently following a tutorial that suggests loading the script after the body for certain reasons. In my own code, I found that I need to place the script both in the head section and after the body. Remov ...

Repeatedly triggering the Jquery Dialog Event

When I open a calendar plugin in jquery dialog, I encounter a recurring issue. Every time I close and reopen the dialog, my calendar event onDayClick triggers multiple times – twice, thrice, and so on. <div id="show_calendar"> <div class="c ...

Async reaction in MobX is a powerful tool for handling

Hey there, I am currently utilizing MobX in a store and faced with the need for an asynchronous reaction to occur when a computed value changes: class Store { @observable user; @observable something; @computed get firstParam () { ret ...

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Message display showing an "[object Object]" (Node Express Passport)

Having an issue with my passport.js implementation where the flash message is not showing up when the username or password is incorrect. The logic was working fine before, but now it's broken even after copying the working version step by step. Flash ...

Avoid working on the script for the element in the partial view during the event

In my index.cshtml view, I have a script that triggers an AJAX call when the SearchingManagerId2 element is changed. $("#SearchingManagerId2").on("change", function () { var valueForSearch = $(this).val(); $.ajax({ ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

React scroll not triggering class changes

In the function handleScroll, I am attempting to add a class of red when scrolling down to a specific limit, otherwise applying a class of blue. However, it seems that it is only entering the else statement and also logging undefined for e.target.scrollTop ...

Refreshing data in AngularJs is like pressing the reset button for

My database contains a list of customers who joined in different years. I have configured my API accordingly and it works smoothly. The issue I am facing is that when using AngularJS to pull the data with the same route (/customers/:id), it doesn't re ...

Ways to remove a JSON item based on its index position?

In my JSON object, I am trying to find a way to remove the first element. Here is an example of what I have: var obj1 = {property:'something', does:'somethingElse', is:'somethingCool'}; var obj2 = {does:'somethingElse&ap ...