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

Sharing data between AngularJS and D3 with JSON - a guide

When working on my application controller, I typically send a request to my API. This is what it usually looks like: .state('state1', { url: '/datas/:id', templateUrl: 'myurl.com', title: 'title', ...

active option in Opencart 2.1 is set to "selected"

I've implemented the AJAX module d_quickcheckout to speed up the checkout process on opencart 2.1 (not the default one). However, I'm encountering an issue with a field in the payment address section that is always pre-selected with the region/st ...

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

Having trouble getting NPM environment variables to function properly on a Windows system?

I have a confusion in my package.json file where I am attempting to compile less code using versioning. Here is an example of what I am trying to achieve: "scripts" { ... "build:css": "lessc --source-map css/index.less build/$npm_package_name.$npm_package ...

Ways to determine the presence of a value in an array using AngularJs

I'm currently working on looping through an array to verify the existence of email, phone, and alternate phone in a database. My challenge lies in finding a suitable function or workaround in AngularJS that allows me to iterate through the array with ...

Create a regular expression in Javascript that only matches strings that do not contain any periods

Struggling with setting up an express route for localhost:3000/test and utilizing regex to handle specific URL patterns. Need assistance combining regex with Express params functionality. router.get('/test/:path[\s^.]*$', function () { ...

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

Validating Two DateTime Pickers as a Group with Javascript in asp.net

How to Ensure Group Validation of Two DateTime Pickers Using JavaScript in ASP.NET ...

Outdated JavaScript Alert

Is it possible to use JavaScript to create an alert message in my input field when a past date is selected? I would like the warning to say "past date, please enter a valid date." <html lang="en"> <head> <meta charset="U ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Executing a function on page load instead of waiting for user clicks

I've been researching a problem with onclick triggers that are actually triggered during page/window load, but I haven't been able to find a solution yet. What I need is the ID of the latest clicked button, so I tried this: var lastButtonId = ...

How can you access additional fields beyond what is displayed in a dropdown select menu in React?

I am working with an array of Jsons that contain the fields ID, name, and description. My goal is to create a dropdown selection box that will show both the name and description when clicked, and then store the associated ID in the rawID state. I have been ...

Embed images within the JavaScript bundle

Here is my scenario: I have developed a components library for React. Within this library, there is a package bundled with Rollup that contains various assets, including a GIF picture used in one of the components. The specific component utilizing this p ...

Obtaining the source code in CKEditor while in edit mode with Rails

As a Rails developer, I recently utilized CKEditor in one of my applications. After writing a sample HTML source code in the editor and submitting it, the code displayed properly on the front-end as a GUI. However, when attempting to edit the source code f ...

"Exploring the capabilities of Rxjs ReplaySubject and its usage with the

Is it possible to utilize the pairwise() method with a ReplaySubject instead of a BehaviorSubject when working with the first emitted value? Typically, with a BehaviorSubject, I can set the initial value in the constructor allowing pairwise() to function ...

What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet: navigator.geolocation.watchPosition( this.updateLocation.bind(this), this.errorLocation.bind(this), {enableHighAccuracy: true} ); The function updateLocation ...

Is it considered poor form to use res.locals in Node.js with Express?

Is it considered bad practice to use res.locals as shown in this code example? Are there potential issues that could arise from using it in this manner? app.use((req, res, next) => { const session = req.cookies.session if (session) { db. ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...