When trying to read a file in react application with webpack Uncaught TypeError: fs__WEBPACK_IMPORTED_MODULE_16___default.a.readFile is not a function

Asked
Active3 hr before
Viewed126 times

7 Answers

tryingfunctionuncaughttypeerrorreact
90%

Iam trying to use fs in my react application to read a file from my local. The code looks like this, Am using target and node attributes as suggested in other articles, still I get the type error, Can't we use fs in react application with webpack? Thoughts?,Connect and share knowledge within a single location that is structured and easy to search.,Making statements based on opinion; back them up with references or personal experience.

Pretag
 Pretag team - issue, fix, solve, resolve
88%

I am using your example to read data and getting an error with the following Error on line 26 of index.js 26 | fs.readFile(file, options, function (err, data) {,I have installed node and npm on a new machine that I wasn't using before. Only thing in common is Windows 10. Still the same error at the same line when trying to read or write.,using the following example:

var jsonfile = require('jsonfile')
var file = '/tmp/data.json'
jsonfile.readFile(file, function(err, obj) {
   console.dir(obj)
})
load more v
72%

Turn on watch mode. This means that after the initial build, webpack will continue to watch for changes in any of the resolved files.,Add a delay before rebuilding once the first file changed. This allows webpack to aggregate any other changes made during this time period into one rebuild. Pass a value in milliseconds:,Verify that you have enough available watchers in your system. If this value is too low, the file watcher in Webpack won't recognize the changes:

webpack.config.js

module.exports = {
   //...
   watch: true,
};

webpack.config.js

module.exports = {
   //...
   watchOptions: {
      aggregateTimeout: 200,
      poll: 1000,
   },
};

Add a delay before rebuilding once the first file changed. This allows webpack to aggregate any other changes made during this time period into one rebuild. Pass a value in milliseconds:

module.exports = {
   //...
   watchOptions: {
      aggregateTimeout: 600,
   },
};

webpack.config.js

module.exports = {
   //...
   watchOptions: {
      ignored: /node_modules/,
   },
};

webpack.config.js

module.exports = {
   //...
   watchOptions: {
      ignored: '**/node_modules',
   },
};

webpack.config.js

module.exports = {
   //...
   watchOptions: {
      ignored: ['**/files/**/*.js', '**/node_modules'],
   },
};

In addition, you can specify an absolute path:

const path = require('path');
module.exports = {
   //...
   watchOptions: {
      ignored: [path.posix.resolve(__dirname, './ignored-dir')],
   },
};

webpack.config.js

module.exports = {
   //...
   watchOptions: {
      poll: 1000, // Check for changes every second
   },
};
module.exports = {
   //...
   watchOptions: {
      followSymlinks: true,
   },
};

Verify that webpack is not being notified of changes by running webpack with the --progress flag. If progress shows on save but no files are outputted, it is likely a configuration issue, not a file watching issue.

webpack--watch--progress

Verify that you have enough available watchers in your system. If this value is too low, the file watcher in Webpack won't recognize the changes:

cat / proc / sys / fs / inotify / max_user_watches
load more v
65%

Most React apps will have their files “bundled” using tools like Webpack, Rollup or Browserify. Bundling is the process of following imported files and merging them into a single file: a “bundle”. This bundle can then be included on a webpage to load an entire app at once.,This will automatically load the bundle containing the OtherComponent when this component is first rendered.,To avoid winding up with a large bundle, it’s good to get ahead of the problem and start “splitting” your bundle. Code-Splitting is a feature supported by bundlers like Webpack, Rollup and Browserify (via factor-bundle) which can create multiple bundles that can be dynamically loaded at runtime.

// app.js
import {
   add
} from './math.js';

console.log(add(16, 26)); // 42
load more v
75%

Arrow functions were introduced in ES6 / ECMAScript 2015, and since their introduction they changed forever how JavaScript code looks (and works).,Production mode is slower to build, since it needs to generate a more optimized bundle. The resulting JavaScript file is smaller in size, as it removes many things that are not needed in production.,To solve the problem we talked about in the introduction (using arrow functions in every browser), we can run

Pretag
 Pretag team - issue, fix, solve, resolve
40%

Pretag
 Pretag team - issue, fix, solve, resolve
22%

entry2.bundle.js which contains the complete code from entry2.js, a requirement for jquery and does not contain the runtime,entry1.bundle.js which contains the complete code from entry1.js, a requirement for jquery and does not contain the runtime,So with this setup, I run npm run dev. The webpack-dev-server starts up, the module loader test works (i.e. when I save any .vue file it causes webpack to recompile), but:

As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in package.json in the root folder, in a property named scripts. There you will mostly encounter commands like babel-node tools/run start. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file tools/run (run.js file located in tools) - basically a runner utility. This runner takes a function as an argument and executes it, which in this case is start - another utility (start.js) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).
Speaking more precisely, start.js creates both client and server side bundles, starts express server and after successful start inits Browser-sync, which at the time of writing looked like this (please refer to react starter project for the newest code).

const bs = Browsersync.create();
bs.init({
         ...(DEBUG ? {} : {
            notify: false,
            ui: false
         }),
         proxy: {
            target: host,
            middleware: [wpMiddleware, ...hotMiddlewares],
         }, // no need to watch '*.js' here, webpack will take care of it for us,      // including full page reloads if HMR won't work      files: ['build/content/**/*.*'],}, resolve)

The important part is proxy.target, where they set server address they want to proxy, which could be http://localhost:3000, and Browsersync starts a server listening on http://localhost:3001, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property fileswith individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.
Now I don't have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like

gulp.task('bundle', function() { // bundling source files with some gulp plugins like gulp-webpack maybe});gulp.task('start', function() {  // starting server and stuff});
load more v

Other "trying-function" queries related to "When trying to read a file in react application with webpack Uncaught TypeError: fs__WEBPACK_IMPORTED_MODULE_16___default.a.readFile is not a function"