The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the error

Uncaught ReferenceError: require is not defined
when I open the web application in the browser.

I can confirm that I am not specifying target: 'node'.

I am not including webpack-node-externals.

I am not explicitly excluding any files from the bundle.

I am not utilizing noParse.

As a test, I even set target: 'web' explicitly (even though it's the default) just to see if anything changed.

The content of my webpack.config.json file is as follows:

const path = require('path');

module.exports = {
  mode: 'production',
  entry: './src/main/webapp/resources/app/template.core.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'src/main/webapp/resources/dist')
  }
};

Here is a snippet from my package.json file:

{
  (...)
  "main": "src/main/webapp/template.core.js",
  "dependencies": {
    "angular": "^1.6.10",
    "angular-animate": "^1.6.10",
    "angular-route": "^1.6.10",
    "angular-sanitize": "^1.6.10",
    "angular-upload": "^1.0.13",
    "ui-select": "^0.19.8",
    "angular-ui-bootstrap": "^2.5.0",
    "moment": "2.22.2"
  },
  "devDependencies": {
    "npm": "^5.6.0",
    "webpack": "^4.26.1",
    "webpack-cli": "^3.1.2",
    "jshint": "^2.9.6"
  },
  "scripts": {
    "lint": "jshint src/main/webapp --exclude src/main/webapp/resources/static,src/main/webapp/resources/dist",
    "build": "webpack"
  },
  (...)
}

I'm at a loss. Can anyone identify where I might be going wrong?

Answer №1

It turns out that my issue stemmed from a simple mistake of including the wrong <script> tags in the html file due to differences in bundle filenames between development and production modes in my webpack setup. To solve this, I started using the html-webpack-plugin to generate the correct includes. I created an empty template file with just a comment to ensure only script tags are outputted. Here's a snippet from my updated webpack.config.js:

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

  ...

  plugins: [
    new HtmlWebpackPlugin({
      template: 'path/to/empty/template',
      filename: 'path/to/templated/output'
    })
  ],

  ...

};

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

Is a Promise nested within another Promise?

My current task involves retrieving the lat/long of 2 addresses using promises. Once this initial promise is resolved, I need to parse a file that correlates with these lat/long coordinates. Everything works as expected and I can handle the values in the ...

What could be causing the continuous occurrence of the error message stating "Module 'socket.io' cannot be found"?

For the past few days, I've been attempting to incorporate socket.io into my NodeJS script. However, every time I run it, I encounter the frustrating error message stating "Cannot find module 'socket.io'". The detailed error is as follows: ...

Retrieving the value from a vuetify v-text-field to use in another text field

Looking to suggest a username based on the user's first and last name. The concept is that after the user fills out the first name and last name fields, the value in the username field will be a combination of their first and last names. firstName = B ...

Error in AngularJS when attempting to add a new field within a for loop

I encountered an issue while attempting to add a new "field" into an array. It seems to stop at a specific number of objects within the array. For example, if my array contains 33 objects, the addition stops at the 7th object. This is a snippet of my Java ...

Require assistance to resolve variable scope problems

Having trouble accessing the names array within the driver.executeScript method. Any suggestions on how to resolve this issue? var webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until; var driver = new webdri ...

Struggling to dynamically fill the table with Ajax Json data

After retrieving data from my webservice call, I am sending this JSON response: [ [ { "id": 123, "vendorName": "PoppyCounter", "item": "Chocolate" }, { "id": 1234, "ve ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

Node Express for Advanced Routing

I'm currently developing a web application that will handle CRUD operations on an array within a collection. Here is the structure of the collection model: var mongoose = require('mongoose'); var website = require('./website'); ...

Issue encountered while consolidate javascript files into a single bundle

I'm attempting to consolidate all of my JavaScript files into one file using the npm run build command (which internally uses browserify and babelify). However, I'm encountering an error. Can you tell me what I might be missing? npm output: ...

Ways to Close a Modal in Ionic 5

I have a scenario where I need to open a modal, perform an asynchronous action, and then automatically dismiss the modal once the action is completed. Specifically, I want to use the fetchData function to handle the async task. @Component({ }) export cla ...

Discover the complete guide on incorporating a JavaScript library with additional dependencies in Angular 2

I am a beginner with angular 2 and I am attempting to integrate the Miso Dataset JavaScript library into my angular 2 project. The Miso library requires other JavaScript libraries as dependencies. Although I have included all the necessary JavaScript file ...

Issues with validating the Google Maps API JavaScript tag

Currently working on updating a website to be fully validated with HTML5 using W3C standards. Having trouble validating the Google Maps API JavaScript tag in the code snippet below: <script src="http://maps.googleapis.com/maps/api/js?libraries=places& ...

Issues arise with the functionality of Zurb Foundation 5 tabs

Utilizing the tabs feature in ZURB Foundation 5, I've noticed that clicking on a tab changes the hash in the URL. However, I actually want to prevent this behavior as I rely on the hash for managing page loads. Although I attempted to use preventDef ...

What is the best way to extract the body content from a Markdown file that includes Frontmatter

How can I retrieve the content of the body from my markdown file using front matter? Currently, it is displaying as undefined. What steps should I take to fix this issue? {latest.map(({ url, frontmatter }) => ( <PostCard url={url} content={frontmat ...

Guide for transferring information from JavaScript to PHP on the same page

My dilemma lies in transferring data from my JavaScript script to PHP code for use within a query. Despite numerous attempts, I have been unsuccessful in achieving this. Below is my script for uploading files using an input type: file, where the URL is sto ...

Flexbox Resizing Notification(?)

Recently, I've been utilizing flexbox in my layout design and it has been a game-changer. However, I am facing an issue that might be linked to my heavy use of AngularJS, particularly the ng-include feature. The specific problem arises when I incorpo ...

When running npm start on a Windows system, an error message stating "Node.js version 14.9.0 detected" is displayed

Encountering an error with the npm start command: Node.js version v14.9.0 detected. The Angular CLI requires a minimum Node.js version of either v14.15, or v16.10. Please update your Node.js version or visit https://nodejs.org/ for additional instructions ...

What is the best way to generate dynamic components on the fly in ReactJS?

Could you please guide me on: Techniques to dynamically create react components, such as from simple objects? Is it possible to implement dynamic creation in JSX as well? Does react provide a method to retrieve a component after its creation, maybe b ...

The required validator in Mongoose is not being triggered by the function

I'm trying to use a function as a validator in a mongoose schema, but it doesn't seem to work if I leave the field empty. The documentation states: Validators are not run on undefined values. The only exception is the required validator. You ...