简体   繁体   中英

Uncaught ReferenceError: require is not defined on webpack setup

I am playing around webpack and react.

Basically, I have the two files utils.js and app.js file sitting under my src folder.

Here's the content of my utils.js file:

const square = (x) => x * x;

export { square };

Here's my app.js file:

import { square } from './utils.js';

console.log('i Hello from app.js here!');

console.log(square(4));

When I run my app via yarn run build it gave me this error:

app.js:3 Uncaught ReferenceError: require is not defined
    at app.js:3

I checked out my webpack.config.js :

const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
      path: path.join(__dirname, 'public'),
      filename: 'bundle.js'
  }
};

I think I am doing good. What's wrong with my code? What does require even means?

You're trying to use a CommonJS module from within your browser. This will not work. How are you using them? When you write import... from... in ES6 Babel will transpile these calls to a module definition called CommonJS and since CommonJS isn't around in the browser you'll get an undefined error from require(). If you want to use CommonJS modules in your code base you need to first bundle them with either Browserify or webpack. The two tools will transform your require calls to some glue magic that you can use within the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM