Node cannot find module "fs" when using webpack

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
}

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.


I had the same issue when bundling a NWjs application using webworkers (which in turn had node enabled).

The solution I found was to include each native module I used in externals with the prefix commonjs to the name of the module. For example:

    ...
    target: "webworker", // or 'node' or 'node-webkit'
    externals:{
        fs:    "commonjs fs",
        path:  "commonjs path"
    }
    ...

I've done the same for targets "webworker" and "node-webkit" in different projects to solve the same issue.

webpack nwjs webworker nodejs node