简体   繁体   中英

ReactJS with Webpack: Uncaught ReferenceError: require is not defined

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;

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.

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