node.jswebpack

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?


Solution

  • 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.