MG Developer
MG Developer

Reputation: 918

webpack-cli ReferenceError: require is not defined

The issue is my webpack config uses CommonJS syntax but main code is written in ES6. However based on the tutorials I have seen online, that seems to be the typical setup. So while the error is obvious, I am unable to determine why is this not working out for me? I would prefer to use CommonJS for webpack because of that is what the documentation uses. But I would like to use ES6 for the code.

My configuration is as follows. Package.json

{
    "name": "my-project",
    "version": "1.22.11",
    "type": "module",
    "dependencies": {
        "html-webpack-plugin": "^5.3.2",
        "react": "^17.0.1",
        "react-dom": "^17.0.1",
        "react-router-dom": "^5.2.0"
    },
    "scripts": {
        "build": "webpack --config webpack/webpack.config.dev.js",
        "test": "jest",
        "dev": "yarn build && cross-env NODE_ENV=dev node ./src/index.js"
    },
    "devDependencies": {
        "@babel/preset-env": "^7.15.0",
        "@babel/preset-react": "^7.14.5",
        "babel-core": "^6.26.3",
        "babel-jest": "^26.6.3",
        "babel-loader": "^8.2.2",
        "cross-env": "^7.0.3",
        "css-loader": "^6.2.0",
        "enzyme": "^3.11.0",
        "enzyme-adapter-react-16": "^1.15.6",
        "enzyme-to-json": "^3.6.1",
        "jest": "^26.6.3",
        "mini-css-extract-plugin": "^2.2.0",
        "webpack": "^5.50.0",
        "webpack-cli": "^4.7.2"
    }
}

webpack configuration

const path = require("path");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
    entry: "./index.js",
    target: "web",
    mode: "development",
    output: {
        filename: "bundle-web.js",
        path: path.resolve(__dirname, "../dist"),
    },
    plugins: [new HtmlWebpackPlugin(), new MiniCssExtractPlugin()],
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: ["/node_modules/"],
                use: {
                    loader: "babel-loader",
                },
            },
            {
                test: /\.css$/i,
                use: [MiniCssExtractPlugin.loader, "css-loader"],
            },
        ],
    },
    resolve: {
        extensions: ["*", ".js", ".mjs"],
    },
};

babelrc

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

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Title</title>
</head>

<body>
    <div id="app"></div>
    <script src=bundle-web.js"></script>
</body>

</html>

index.js (proprietary code excluded).

import * as React from 'react'; 
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; 
import ReactDOM from 'react-dom'; import './index.css';

Node version: v13.14.0 OS: Windows 7. (Yes I know should replace it, but I don't believe OS is the problem here). Yarn: 1.22.5

The bundle is created as I can see in the dist folder but when I run "yarn dev"

I am getting the following error. I tried all kinds of solutions of google, github and stackoverflow no luck.

webpack --config webpack/webpack.config.dev.js
webpack-cli] Failed to load \project\webpack\webpack.config.dev.js' config
webpack-cli] ReferenceError: require is not defined
   at file:///project/webpack/webpack.config.dev.js:1:14
   at ModuleJob.run (internal/modules/esm/module_job.js:110:37)
   at async Loader.import (internal/modules/esm/loader.js:179:24)
   at async importModuleDynamicallyWrapper (internal/vm/module.js:422:15)
   at async WebpackCLI.tryRequireThenImport (project\node_modules\webpack-cli\lib\webpack-cli.js:57:26)
   at async loadConfig project\webpack-cli\lib\webpack-cli.js:1536:27)
   at async project\webpack-cli\lib\webpack-cli.js:1589:36
   at async Promise.all (index 0)
   at async WebpackCLI.resolveConfig project\node_modules\webpack-cli\lib\webpack-cli.js:1587:38)
   at async WebpackCLI.createCompiler project\node_modules\webpack-cli\lib\webpack-cli.js:2045:22)

Upvotes: 2

Views: 6669

Answers (3)

MG Developer
MG Developer

Reputation: 918

I am answering my own question in a hope that it can help someone running into the same issue. Basically the issue was my thought process was reversed. You can either choose ES6 or Common JS for your entire code base. When you do that all files including webpack config files are treated the same page. By defining type: module, I was saying all my code base including the webpack config now becomes ES6 syntax, hence I was getting the above error. So I removed type:module stating that all my code base including the webpack configuration files should be treated as Common JS, even though my source code is written in ES6. Then I used babel to transpile my ES6 import statements of my actual source (not the webpack config since its already written in common JS) into common JS and that resolved the issue, which was rather not an issue but basic misunderstanding.

The second alternative was to use type:module to state that it's a ES6 and then use import statements and ES6 equivalent code to write the webpack configuration. However because most of examples in Webpack were in common JS, I chose the former option, because I am sort of new to JavaScript and I wanted to avoid any basic mistakes such as this. So in a nutshell there was a misunderstanding on my part, I hope this comment helps newbie JS developers. Thank you!

Upvotes: 5

Bibek Timalsina
Bibek Timalsina

Reputation: 61

In my case I got same error and i found that i have misconfigure the webpack.config.js file. The provided context and path for output should be same.

webpack.config.js

 module.exports={
        context: __dirname,
        entry: "./app.js",
        output: {
              path: __dirname + "/dist",
              filename:"bundle.js"
        }
    }

Upvotes: 0

Attila
Attila

Reputation: 91

I haven't verified this with node 13.x but in the stable 14.x and up whenever "type" is defined with value "module", it tells Node.js to interpret .js files within that package as using ES module syntax, see documentation.

I'd either try removing the "module" declaration from the package.json, and stick to CommonJS in webpack, or use import/export clauses in webpack and see which works best.

However, I'd also aim to use a stable nodejs branch, i.e 14.x or 16.x as 13.x are considered unstable

Upvotes: 0

Related Questions