Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node cannot find module "fs" when using webpack

I'm using node.js and webpack to create a bundle. From what I've read, node.js should contain fs module for managing files. However when I call require("fs") I get an Cannot find module "fs" error. What should I do?

like image 709
user3799968 Avatar asked Aug 31 '16 12:08

user3799968


People also ask

Can t find module fs?

To solve the "Cannot find module fs or its corresponding type declarations" error, install the types for node by running the command npm i -D @types/node . You can then import fs with the following line of code import * as fs from 'fs' .

Where is Webpack config JavaScript?

The webpack configuration file webpack. config. js is the file that contains all the configuration, plugins, loaders, etc. to build the JavaScript part of the NativeScript application. The file is located at the root of the NativeScript application.


2 Answers

I came across this problem myself when bundling with webpack and found the answer on this thread.

The way to solve it for me was to use the following config:

module.exports = {   entry: "./app",   output: {     path: __dirname,     filename: "bundle.js"   },   module: {       loaders: [           {                 test: /\.js$/,               exclude: 'node_modules',               loader: 'babel',               query: {presets: ['es2015']},           }       ]   },   target: 'node' }; 

By setting target to node webpack will make the necessary changes to bundle your node application

Edit: This answer targeted webpack 1.x which has now been superseded.

like image 177
Joe Withey Avatar answered Sep 30 '22 07:09

Joe Withey


If you are running your webpack bundle in nodejs environment then target: 'node' is required in webpack.config.js file otherwise webpack takes default value as web for target check here.

You can resolve the issue in two ways

Add below configuration to your webpack.config.js

node: {     fs: "empty" } 

OR

Add below configuration to your package.json

"browser": {     "fs": false } 

Edit:

promising fix is

"browser": {    "fs": false } 
like image 39
Hemadri Dasari Avatar answered Sep 30 '22 06:09

Hemadri Dasari