title: Webpack Uncaught ReferenceError: require is not defined after removing node_modules from bundle.js
body: <pre><code>bundle.js      2.83 kB   0  [emitted]  main
  bundle.js.map  3.36 kB   0  [emitted]  main
  </code></pre>
  
  <p>When I add the code below with the custom externals, I can remove the <code>node_modules</code> from being directly included in the <code>bundle.js</code> output. </p>
  
  <pre><code>bundle.js      743 kB       0  [emitted]  main
  bundle.js.map  864 kB       0  [emitted]  main
  </code></pre>
  
  <p>This significantly reduces the bundle size. <strong>But I get an error in the browser saying:</strong> <code>Uncaught ReferenceError: require is not defined</code> in the browser. Does anyone know how to fix this issue?</p>
  
  <pre><code>var path = require("path"),
    fs = require("fs");
  
  // return what's in the node modules folder apart from ".bin"
  const nodeModules = fs
    .readdirSync("./node_modules")
    .filter(d =&gt; d != ".bin");
  
  /**
   * Remove non-direct references to modules from bundles
   *
   * @param {any} context
   * @param {any} request
   * @param {any} callback
   * @returns
   */
  function ignoreNodeModules(context, request, callback) {
    // IF someone is importing a module e.g. "import {chatModule} from
    // "./components/chat" using a relative path, then we're okay with them bringing
    // in into the bundle
    if (request[0] == ".") 
      return callback();
  
    // IF someone is doing "import {Subject} from "rxjs/Subject" only want to know
    // if first part is a node_module
    const module = request.split("/")[0];
    if (nodeModules.indexOf(module) !== -1) {
      // append "commonjs " - tells webpack to go and grab from node_modules instead
      // of including in bundle
      return callback(null, "commonjs " + request);
    }
  
    return callback();
  }
  
  module.exports = {
    entry: "./src/index.tsx",
    output: {
      filename: "bundle.js"
    },
    devtool: "source-map",
    resolve: {
      extensions: ["", ".ts", ".tsx", ".js"]
    },
    module: {
      loaders: [
        {
          test: /\.ts(x?)$/,
          loader: "ts-loader"
        }
      ]
    },
    // Runs our custom function everytime webpack sees a module
    externals: [ignoreNodeModules]
  }
  </code></pre>