In my code, I never use the term "require", yet webpack continues to generate the error message "require is not defined."

I am in the process of developing an electron app using react. To run the development version, I use the following command:

webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js

Displayed below is the webpack.dev.config.js file:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { spawn } = require('child_process');
const helpers = require('./config/helpers');

// Configuration directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'dist');

// Include any directories where you will be adding code or files into this array so webpack can recognize them
const defaultInclude = [SRC_DIR];

module.exports = {
  entry: SRC_DIR + '/index.js',
  output: {
    path: OUTPUT_DIR,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
        include: defaultInclude
      },
      {
        test: /\.jsx?$/,
        use: [{ loader: 'babel-loader' }],
        include: defaultInclude
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
        include: defaultInclude
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
        include: defaultInclude
      }
    ]
  },
  target: 'electron-renderer',
  plugins: [
    new HtmlWebpackPlugin({
      template: helpers.root('public/index.html'),
      inject: 'body'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],
  devtool: 'cheap-source-map',
  devServer: {
    contentBase: OUTPUT_DIR,
    stats: {
      colors: true,
      chunks: false,
      children: false
    },
    setup() {
      spawn(
        'electron',
        ['.'],
        { shell: true, env: process.env, stdio: 'inherit' }
      )
      .on('close', code => {
        console.error("electron exited with code ", code);
        process.exit(0)
      })
      .on('error', spawnError => console.error(spawnError));
    }
  }
};

Upon opening the electron browser, the Dev-Tools console displays the following error:

Uncaught ReferenceError: require is not defined
    at Object.url (index.js:23)
    at __webpack_require__ (bootstrap:709)
    at fn (bootstrap:94)
    at Object../node_modules/webpack-dev-server/client/utils/createSocketUrl.js (createSocketUrl.js:4)
    at __webpack_require__ (bootstrap:709)
    at fn (bootstrap:94)
    at Object.<anonymous> (client:20)
    at Object../node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:4000 (client:176)
    at __webpack_require__ (bootstrap:709)
    at fn (bootstrap:94)

The location where the error supposedly occurs is index.js:23.

Here is the build version of index.js:

import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { ipcRenderer as ipc } from "electron";
import { onUpdate } from "./actions/workerActions";
import { RECEIVED_STATE } from "./actions/types";
import "./assets/css/index.css";
import rootReducer from "./reducers/rootReducer";
import defaultState from "../config/defaultstate"; //Setup redux store

const middleware = [thunk];
const store = createStore(rootReducer, defaultState, applyMiddleware(...middleware));
ipc.on(RECEIVED_STATE, arg => {
  console.log("Recieved State: ", arg);
  onUpdate(arg)(store.dispatch);
}); // Now we can render our application into it

render(React.createElement(Provider, {
  store: store
}, React.createElement(App, null)), document.getElementById("app"));

It's worth noting that the import statement does not contain `require` and all the imports except for `ipcRenderer` are meant to execute client-side, thus should not involve `required`. I even attempted to comment out the `ipcRenderer` import, but the error persisted.

Interestingly enough, even with the entire index.js file disabled, the very same error persists. The console insists on a reference to `require`, which is undefined.

Answer №1

The issue stemmed from importing electron's ipcRenderer, which necessitates node integration and relies on require. The failure to resolve the error by commenting out the import in index.js was due to its usage in other modules.

Answer №2

If you are working directly with webpack, ensure that your webpack configuration targeting the renderer code includes the following:

// webpack.config.js
...
module.exports = {
 ...
 target: 'web',
 ...
}

For Vue users, a similar setup is required:

// vue.config.js
...
module.exports = {
 ...
 configureWebpack: {
   target: 'web'
 },
 ...
}

In my case, I utilized the vue-cli-plugin-electron-builder and needed the following configuration:

// vue.config.js
...
module.exports = {
  ...
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: false,
      chainWebpackRendererProcess: config => {
        config.target('web');
      }
    }
  },
  ...
}

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

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

Canvas drawImage function not displaying image at specified dimensions

I'm having trouble loading an image into a canvas using the drawImage function. Additionally, I've implemented drag functionality but found that when moving the image inside the canvas, it doesn't follow the mouse cursor in a linear manner. ...

Ways to reduce the amount of time spent watching anime when it is not in view

My anime experiences glitches as the black container crosses the red, causing a decrease in duration. Is there a way to fix this glitch? I attempted to delay the changes until the red path is completed, but the glitches persist. delayInAnimeSub = ourVilla ...

Different browsers have varying ways of handling transition end callbacks with AddEventListener()

Each browser has its own transition end callback. Therefore, I find myself needing to use addEventListener() for each one. addEventListener('transitionend', function() { // code here }); addEventListener('webkitTransitionEnd', funct ...

Running a function on a specific route within the same file in Node.js - here's how to do it

I am looking to execute a function on a specific route that is defined within the same file. module.exports.controller = function(app) { app.get('/folders/create', createDirectory); } var createDirectory = function(path, name, permissions, v ...

Monitoring the "signed in" status within an AngularJS platform

I'm feeling a bit lost as I navigate my way through Angular. As a newcomer, I find myself writing quite a bit of code to keep track of the logged-in state. However, this approach seems fragile and unreliable. Currently, I rely on a global variable to ...

Pressing the submit button within a form in Ionic2 triggers the Ion-Input onSubmit event

In my form, there is an ion-button and an ion-input included. The ion-button is not meant for submitting the form. When I try to edit a value in the input field and press "ok", I expect the keyboard to hide. However, the ion-button reacts to this event an ...

What are the steps to add code into the Monaco Editor using Playwright?

As I explore the world of Playwright, I am faced with a challenge regarding testing a feature that involves a monaco editor. Unfortunately, my search in Playwright documentation and forums did not yield any relevant information. Here is the test scenario ...

Is there a way to customize the appearance of an unordered list by setting it to display as an image instead of default bullets? I want to

I have been attempting to achieve this desired outcome. However, my efforts to reproduce it resulted in the check marks being rendered at a smaller size than intended due to using an SVG file. An example of this issue can be seen in the following image: I ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

Customizing Javascript for Mouse Exiting Browser Window

I have implemented a JavaScript function on my website to display a lightbox when the visitor's mouse goes beyond the browser window. You can check it out here: [http://mudchallenger.com/index-test2.html][1] However, there seems to be an issue where ...

Searching for values in nested arrays using lodash.find

Presented below is an array where I aim to employ lodash for item search: [ { "itemA": "apple", "itemB": [ { "itemC": "1", "itemD": "red apple" }, { "itemC": "2", "itemD": "green apple" }, ...

I desire to receive comments only once since they are being rehashed repeatedly

On the server-side: This is where I retrieve the comment from the server db.postSchema .findOne({ _id: comment.post }) .populate("owner") .exec((err, users) => { for (let i = 0; i < ...

Displaying a div based on the response after it is received using an if/else statement

In my form, each question is on a separate page (div), with the ability to show and hide pages. If a user receives a response from the API with a status of "accepted", they are redirected to a URL. I'm currently trying to display a div if their status ...

Keep your Vue table continuously updated in real-time

While I have come across similar questions like this and this, my issue presents a unique challenge. I am polling data for a table every second from my REST Api using axios. Despite this, I want the user to be able to freely manipulate (e.g. order, sort, ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

Ways to prevent a loop from constantly restarting

After clicking the generate ID button once, it will become disabled and display a set of numbers. The last 4 digits are in a loop sequence starting with "0001". If I were to re-enable the generate ID button and click it again, the last 4 digits would incre ...

Guide on generating virtual nodes from a string containing HTML tags using Vue 3

Investigation I stumbled upon this solution for converting a simple SVG with one path layer into Vue2 vnode list and wanted to adapt it for Vue3. After scouring resources, including the MDN docs, I couldn't find any pre-existing solutions. So, I dec ...

What is the recommended sequence for using decorators in NestJS: @Body(), @Params(), @Req(), @Res()?

How can I properly access the res object to send httpOnly cookies and validate the body with DTO? I keep running into issues every time I attempt it. What is the correct order for these parameters? ...

Looking to enhance code by using jQuery to substitute numerous href elements. Only seeking enhancements in code quality

I am currently using regular JavaScript to change the href of 3 a-tags, but I want to switch to jQuery for this task. var catNav = $('ul.nav'), newLink = ['new1/','new2','nwe3/']; catNav.attr('id','n ...