5

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!

12
  • How are you "building"? . It looks like you are just including the script in the browser's <script> tag. require only works in a node environment. After the build process, the transformed javascript will be understood by the browser. If you edit your answer to include what buildsteps you are running, I could look into it more. also, are there any scripts in your package.json? Commented Oct 1, 2018 at 8:35
  • @axm__ Thanks for your comment. I updated my question. Commented Oct 1, 2018 at 10:00
  • Your package.json mentions { build: webpack }. Did you actually run npm run build to run the command? If not, could you do so before I try to answer the question and tell me what the output is. The command should output the built file to the output path you mentioned in webpack.config.json . To read more about npm scripts: michael-kuehnel.de/tooling/2018/03/22/… Commented Oct 1, 2018 at 10:14
  • @axm__ yes, I built the output js file using npm run build. When I add the output js file and add it to <script> tag in browser console I get the error require is undefined. Commented Oct 1, 2018 at 10:43
  • Ok, that is weird. How does your output file look like? Can you see if there is any transform at all? Commented Oct 1, 2018 at 10:55

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem is script.js file can't require other two files. That's why in console I get the error. So, what is the appropriate way to require other two js within script.js?
0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.