Home > Software design >  How do I fix "require is not defined" error with Webpack and Babel?
How do I fix "require is not defined" error with Webpack and Babel?

Time:08-11

I keep getting error Uncaught ReferenceError: require is not defined in browser even with Webpack and Babel. For some reason I never had to worry about this before. I'm not sure if this error is caused by updated packages or what. I set up a very simple test application for simplicity. package.json

{
   "name": "require-test",
   "version": "1.0.0",
   "description": "",
   "main": "index.js",
   "engines": {
      "node": "16.16.0"
   },
   "scripts": {
      "build": "webpack --config webpack.config.js"
   },
   "author": "",
   "license": "ISC",
   "devDependencies": {
      "@babel/core": "^7.18.10",
      "@babel/preset-env": "^7.18.10",
      "babel-loader": "^8.2.5",
      "webpack": "^5.74.0",
      "webpack-cli": "^4.10.0"
   }
}

webpack.config.js

const path = require('path');

module.exports = {
   target: "node",
   mode: "production",
   output: {
      path: path.resolve(__dirname, 'dist'),
      clean: true,
      filename: (pathData) => {
         return 'index.js'
      },
   },
   module: {
      rules: [
         {
            test: /\.m?js$/,
            exclude: /(node_modules|bower_components)/,
            use: {
               loader: 'babel-loader',
               options: {
                  presets: ['@babel/preset-env']
               }
            }
         }
      ]
   }
}

src/index.js (js file before build)

const path = require('path');

console.log(path);

dist/index.js (js file after build)

(()=>{var r,e={17:r=>{"use strict";r.exports=require("path")}},t={};r=function r(o){var s=t[o];if(void 0!==s)return s.exports;var p=t[o]={exports:{}};return e[o](p,p.exports,r),p.exports}(17),console.log(r)})();

CodePudding user response:

There're a few things on your code needing changed. First of all, you can't target to build for node while you run that code on browser which is wrong. Secondly, path is designed and built to run on node server specifically, however, there's a fallback for path on browser though which is called path-browserify. You can check its document to see how it works.

Anyway to sum up, you need to switch target as web in the end:

module.exports = {
 target: "web",
 // ...
}

  • Related