2

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;
user2130898
  • 41
  • 2
  • 7
  • 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 Jun 22 '17 at 09:46
  • is the compiled code going to be used within the browser or node? can you also provide a snippet of main.js? – roughcoder Jun 22 '17 at 10:04
  • Why do you need this node: { fs: "empty" }, and target: node? – VivekN Jun 22 '17 at 10:28

1 Answers1

3

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.

roughcoder
  • 1,190
  • 1
  • 8
  • 11
  • Thanks for you response. – user2130898 Jun 27 '17 at 06:27
  • Using this method, How can I update some-data.json? – user2130898 Jun 27 '17 at 06:28
  • Does the code you are writing need to run in a browser? If so then you need to write 2 applications - 1 in react for example and one for Node. The common practice is that React app can talk to the Node app through APIs. A common Node framework to build these APIs is Express Js. Though take note your API can be written in any server side language - it does not need to be Node. Hope this helps you helps. – roughcoder Jun 28 '17 at 06:52