2
votes

Below is my webpack.config.js. In the browser developer tools, getting "Uncaught ReferenceError: require is not defined"

If I remove "target":"node", then error "Uncaught TypeError: fs.readFileSync is not a function" is thrown.

var config = {
   entry: './main.js',

   output: {
      filename: './index.js',
   },

   devServer: {
      inline: true,
      port: 8080
   },
  node: {
    fs: "empty"
  },

   module: {
      loaders: [
         {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',

            query: {
               presets: ['es2015', 'react']
            }
         }
      ]
   },
  target: 'node'
}
module.exports = config;
1
I don't see any special problem with your webpack config. Maybe you should provide some of the code files that gives the error? - atomrc
is the compiled code going to be used within the browser or node? can you also provide a snippet of main.js? - roughcoder
Why do you need this node: { fs: "empty" }, and target: node? - VivekN

1 Answers

3
votes

You are requiring a native module from node and trying to use it within your browser. In this instance you are requiring fs.

If you are making code for a browser then you are unable to use Nodes fs.readFileSync and you shouldnt use target: 'node'

I can recreate your problem using the following main.js file.

const fs = require('fs');

const test = function () {
    console.log('this is a test');
    var contents = fs.readFileSync('DATA', 'utf8');
}

test();

If you are trying to use an additional file within the browser then you either:

Require the file on build

This will permanently ship the data of the file with your index.js file using require for example. This is perfectly acceptable if the contents is some config and doesnt change per user, examples are language files etc. This method can increase your asset files and hit first time load speeds if the contents on the file is large.

const data = require('some-data.json`)
console.log(data) // would output the JSON

AJAX the content

Using Ajax/Fetch your could call the contents of the file on page load. If this file is meant to be unique for each visitor then you will need to do this.