user3384985
user3384985

Reputation: 3017

Webpack: Uncaught ReferenceError: require is not defined

In my PHP project - I am trying to build my js files using webpack and babel. There are 3 js files - config.js helper.js script.js. They have dependency on each other. helper.js is dependent on config.js and script.js is dependent on helper.js.

config.js:

module.exports = {
  const DG_GRAPH_TYPE = 'line';

  const DG_XAXIS_TICKS = 4;

  const DG_SINGLE_POST_GRAPH_CANVAS_HEIGHT = 250;
  ......



helper.js:

const config = require('./config');

module.exports = {
......



script.js:

const helper = require('./helper');

jQuery(document).ready(function ($) {
......

Here is my wepack.config.js file where I configured with following code:

const path = require('path');

module.exports = {
    entry: {
        script: [
            './assets/js/script.js'
        ]
    },
    output: {
        filename: '[name].bundle.min.js',
        path: path.resolve(__dirname, 'build'),
    },
    resolve: {
        extensions: ['.js', '.css']
    },
    module: {
        rules: [
            {
                test: /\.js/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env'],
                        plugins: [require('@babel/plugin-proposal-object-rest-spread')]
                    }
                },
                parser: {
          amd: false, // disable AMD
          commonjs: false, // disable CommonJS
          system: false, // disable SystemJS
          harmony: true, // disable ES2015 Harmony import/export
          requireInclude: false, // disable require.include
          requireEnsure: false, // disable require.ensure
          requireContext: false, // disable require.context
          browserify: true, // disable special handling of Browserify bundles
          requireJs: true, // disable requirejs.*
          node: false, // disable __dirname, __filename, module, require.extensions, require.main, etc.
        }
            }
        ],
    }
};

Everything works fine except when I add the built script file within project, I get following browser console error -

Uncaught ReferenceError: require is not defined at Object. (script.bundle.min.js?ver=4.9.8:1) at a (script.bundle.min.js?ver=4.9.8:1) at Object. (script.bundle.min.js?ver=4.9.8:1) at a (script.bundle.min.js?ver=4.9.8:1) at script.bundle.min.js?ver=4.9.8:1 at script.bundle.min.js?ver=4.9.8:1

What I was expecting require.js should solve the issue. But it doesn't.

Can you please suggest me the appropriate way to solve the issue?

EDIT

The main concept of the work is just to build multiple js files in one place also adding babel to make it browser friendly if I have to add ES6/ES7.

My main js file is script.js which its has two dependencies config.js and helper.js. So, I was to build only script.js where I wanted to import/require dependencies file there.

At first I tried to entry all js files, but all I got script.js was built not others. -

entry: {
        script: [
            './assets/js/config.js'
            './assets/js/helper.js'
            './assets/js/script.js'
        ]
    },

Here is the package.json -

{
  "name": "GRAPH",
  "version": "1.0.0",
  "description": "Graph plugin",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "author": "ABC",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.1.0",
    "@babel/polyfill": "^7.0.0",
    "@babel/preset-env": "^7.1.0",
    "babel-loader": "^8.0.4",
    "jquery": "^3.3.1",
    "mini-css-extract-plugin": "^0.4.3",
    "requirejs": "^2.3.6",
    "webpack": "^4.20.2",
    "webpack-cli": "^3.1.1",
    "webpack-dev-server": "^3.1.9"
  }
}

Also, yes. I was adding the built js file in <script> tag.

END EDIT

Thanks in advance!

Upvotes: 5

Views: 15857

Answers (3)

Lukasz Dynowski
Lukasz Dynowski

Reputation: 13570

I arrived to the same error but, instead of using webpack I used gulp. Babel transpiled ES6 to ES5 but it failed to comply with import and required statements. In short, gulp-bro library saved my day. You can find step by step instructions in this answare.

Upvotes: 0

axm__
axm__

Reputation: 2673

You need to build the bundle first to make it understandable to the browser. The error require is not defined gives you the hint that you are not in an node environment (it was not called by something like node runthiscurrentprogram.js or by a program that runs node for you. Read more about the output format with require here

Webpack is a bundler that runs in node that can bundle and/or transform source files (could be javascript, css, etc.) and places them where you want. The bundles file can be included in a <script> tag to make it understandable to the browser.

To run webpack either run npm run build (because you have a script named build in your package.json scripts or npx webpack (more about npx here). What this does is call the webpack executable in /path_to_your_project/node_modules/.bin/webpack. If you open that file, you will see it is run in node (it starts with #!/usr/bin/env node)

Now you mention that your main file is script.js which "requires" those other files. In that case you only have to put script.js in the webpack entry. Webpack automatically bundles the required files in the bundle. All the code will be out put in your outputPath in a single file. (There are ways/reasons to have multiple entries, but not in your case I guess, read more here).

So run npm run webpack , npx webpack and look at the output path if there's a new file there and include that file in the <script> tag.

Upvotes: 5

guyot
guyot

Reputation: 363

The require function does not exist in browsers, only in Node environments. Take a look at this.

Upvotes: 0

Related Questions