Search code examples
javascriptnpmwebpackrequirecommonjs

Uncaught ReferenceError: require is not defined Webpack + AngularJS


There's dozens and dozens of questions like this one, and none have helped because the root cause is always something I'm not doing. I'm making a bundle for the browser with webpack 4.26.1, and I keep getting Uncaught ReferenceError: require is not defined when I open the webapp in the browser no matter what I do.

I'm not using target: 'node'.

I'm not requiring webpack-node-externals.

I'm not explicitly excluding anything from the bundle.

I'm not using noParse.

I even tried explicitly setting target: 'web' even though it's the default just to see if anything somehow changed.

This is the entirety of my webpack.config.json:

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')
  }
};

This is my package.json

{
  (...)
  "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"
  },
  (...)
}

What am I doing wrong?


Solution

  • For future reference, my issue was something as basic as having the wrong <script> includes in the html, because due to my webpack configurations, the bundles' filenames are different for development and production modes. I am now using html-webpack-plugin to generate the includes, with my template file being an empty file with just a comment so it outputs nothing but the script tags themselves. Here's how it looks in my webpack.config.js:

    var HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
    
      ...
    
      plugins: [
        new HtmlWebpackPlugin({
          template: 'path/to/empty/template',
          filename: 'path/to/templated/output'
        })
      ],
    
      ...
    
    };