webpack require issue in production; Uncaught ReferenceError: require is not defined

Issue

I have built aapplictaion, using HTML /CSS and Vanilla JS and using express.js to run it. which works great.

now use webpack to build the package with help of several reference on internet, this expack helps me to build, somehow succeeded to build and when run npm run start it works fine in local and works as expected but there is error in console

index.js:1 Uncaught ReferenceError: require is not defined
at 807 (index.js:1:21589)
at webpack_require (index.js:1:22045)
at index.js:1:33214
at index.js:1:33289

which do not stop anything on local but in production, due to this error, user unable to click on any of pages.

digging more into issues it takes me to this line

 807: e=>{
      e.exports = require("webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000")
    }

which cause issue ( it seems )

production URL: https://master.d1v0nmn943cmur.amplifyapp.com

below are required file content, for full code you can see master branch on https://github.com/xkeshav/canvas.git

package.json

{
  "name": "canvas",
  "version": "1.0.0",
  "description": "trying with basic html css",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack --mode development --config webpack.dev.config.js",
    "server": "webpack --mode development --config webpack.server.config.js",
    "clean": "rd /s /q dist >nul 2>&1|echo.>null",
    "start": "node ./dist/server.js",
    "build": "npm run server && npm run dev",
    "build:dev": "webpack --mode=production --config webpack.dev.config.js"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/xkeshav/canvas.git"
  },
  "keywords": [
    "canvas",
    "varnmala",
    "kids learn"
  ],
  "author": "Keshav Mohta",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/xkeshav/canvas/issues"
  },
  "homepage": "https://github.com/xkeshav/canvas#readme",
  "devDependencies": {
    "@babel/core": "^7.20.7",
    "@babel/eslint-parser": "^7.22.9",
    "@babel/register": "^7.0.0",
    "babel-loader": "^9.1.0",
    "copy-webpack-plugin": "^11.0.0",
    "css-loader": "^6.7.3",
    "eslint": "^8.30.0",
    "eslint-webpack-plugin": "^3.2.0",
    "html-loader": "^4.2.0",
    "html-webpack-plugin": "^5.5.0",
    "http-proxy-middleware": "^2.0.6",
    "json-server": "^0.17.1",
    "mini-css-extract-plugin": "^2.7.2",
    "style-loader": "^3.3.1",
    "webpack": "^5.75.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-middleware": "^6.0.1",
    "webpack-hot-middleware": "^2.25.3",
    "webpack-node-externals": "^3.0.0"
  },
  "dependencies": {
    "@babel/preset-env": "^7.20.2",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "path": "^0.12.7",
    "request": "^2.88.2"
  }
}

.babelrc

{
    "presets": [
        "@babel/preset-env"
    ]
}

webpack.dev.config.js

const path = require("path");
const webpack = require("webpack");
const nodeExternals = require("webpack-node-externals");

const plugins = require("./webpack.plugin.config");
const modules = require("./webpack.modules.config");

//console.log(process.argv.mode);
const BUILD_DIR = path.join(__dirname, "dist");
const SERVER_PATH = "/src/server/server-dev.js";
const SERVER_DIR = path.join(process.cwd(), SERVER_PATH);

const baseConfig = {
  entry: {
    index: ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000", "./src/index.js"],
    draw: ["./src/scripts/draw.js", "./src/scripts/alphabet.js", "./src/styles/draw.css"],
    varnmala: ["./src/scripts/varnmala.js", "./src/styles/varnmala.css"],
    canvas: ["./src/scripts/canvas.js", "./src/styles/canvas.css"],
    server: [SERVER_DIR],
  },
  performance: {
    hints: false,
  },
  devServer: {
    hot: true,
    contentBase: path.join(__dirname, "dist"),
  },
  output: {
    path: BUILD_DIR,
    publicPath: "/",
    filename: "[name].js",
    chunkFilename: "[name].js",
    assetModuleFilename: "assets/[hash][ext][query]",
    globalObject: `typeof self !== 'undefined' ? self : this`,
    clean: true,
  },
  mode: "production",
  target: "node", // "web"
  node: {
    // Need this when working with express, otherwise the build fails
    __dirname: false, // if you don't put this is, __dirname and __filename return blank or /
    __filename: false,
  },
  externals: [nodeExternals()],
  devtool: "eval-source-map",
  resolve: {
    extensions: [".html", ".js", ".json", ".css"],
  },
};

const config = Object.assign(baseConfig, { plugins, module: modules });

module.exports = config;

webpack.server.config.js


const path = require("path");
const nodeExternals = require("webpack-node-externals");

const SERVER_PATH = "./src/server/server-dev.js";
const config = {
  entry: {
    server: SERVER_PATH,
  },
  output: {
    path: path.resolve(__dirname, "dist"),
    publicPath: "/",
    filename: "[name].js",
  },
  devServer: {
    hot: true,
    historyApiFallback: true,
  },
  resolve: {
    extensions: [".js"],
  },
  mode: "production",
  target: "node",
  externals: [nodeExternals()], // Need this to avoid error when working with Express
  module: {
    rules: [
      {
        // Transpile ES6-8 into ES5
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
};
module.exports = config;


server/server-dev.js

// @ts-nocheck
import express from "express";
import fs from "fs";
import path from "path";
import { webpack } from "webpack";
import webpackDevMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import config from "../../webpack.dev.config.js";

const app = express();

const router = express.Router();

const currentDirectory = process.cwd(); // current directory

//console.log({ currentDirectory });

const DIST_DIR = path.join(path.resolve(currentDirectory, "dist"));

const HTML_DIR = path.join(DIST_DIR, "html");
const HTML_FILE = path.join(HTML_DIR, "index.html");
const compiler = webpack(config);

app.use(
  webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
  })
);

app.use(webpackHotMiddleware(compiler));

app.use(express.static(HTML_DIR));

app.get("/home", (_, res) => {
  res.sendFile(HTML_FILE);
});

app.get("/about", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "about.html"));
});

app.get("/draw", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "draw.html"));
});

app.get("/varnmala", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "varnmala.html"));
});

app.get("/canvas", (_, res) => {
  res.sendFile(path.join(HTML_DIR, "canvas.html"));
});

const readJson = (fileName) => {
  let jsonObjData = [];
  try {
    const jsonStringData = fs.readFileSync(path.join(DIST_DIR, "json", fileName));
    jsonObjData = JSON.parse(jsonStringData);
  } catch (err) {
    console.log(err);
  }
  return jsonObjData;
};

app.get("/bg/:key", (req, res) => {
  //console.log("params", req.params.key);
  const fileData = readJson("bg.json");
  const output = fileData.filter((f) => f.key === req.params.key.toLowerCase());
  //console.log({ output });
  res.status(200).send(output);
});

app.use("/", router);

const PORT = process.env.PORT || 3003;

app.listen(PORT, () => {
  console.log(`App listening to ${PORT}....`);
  console.log("Press Ctrl+C to quit.");
});

this is the output of run npm run build

npm run build output

below are my few queries:

  1. how to fix this webpack require issue, tried few alternative as suggested on other questions but none works
  2. if there are missing/wrong webpack configuratio then kindly point
  3. Hot reload not working when changes in HTML file but works for css, how to enable that?

Solution

found the solution, the reason of this error was the line in file webpack.dev.config.js

index: ["webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000", "./src/index.js"]

somehow webpack 5 do not support hot-middleware anymore ( as i found) so change this to

index: ["./src/index.js"]

solved my issue.

Answered By – xkeshav

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published