5

I'm using node.js (the last version) 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. I've stuck with 'require is not defined ' in my console after adding "target: 'node' ". Any help will be usefull, thx.

var webpack = require('webpack');

module.exports = {
    entry: "./client/main.js",
    output: {
        path: __dirname + '/public/build/',
        publicPath: "build/",
        filename: "bundle.js"
    },

    node: {fs: "empty"},

    module: {
        loaders: [
            {
                test: /\.js$/,
                loader: "babel",
                exclude: [/node_modules/, /public/]
            },
            {
                test: /\.css$/,
                loader: "style-loader!css-loader!autoprefixer-loader",
                exclude: [/node_modules/, /public/]
            },
            {
                test: /\.less$/,
                loader: "style-loader!css-loader!autoprefixer-loader!less",
                exclude: [/node_modules/, /public/]
            },
            {
                test: /\.gif$/,
                loader: "url-loader?limit=10000&mimetype=image/gif"
            },
            {
                test: /\.jpg$/,
                loader: "url-loader?limit=10000&mimetype=image/jpg"
            },
            {
                test: /\.png$/,
                loader: "url-loader?limit=10000&mimetype=image/png"
            },
            {
                test: /\.svg/,
                loader: "url-loader?limit=26000&mimetype=image/svg+xml"
            },
            {
                test: /\.jsx$/,
                loader: "react-hot!babel",
                exclude: [/node_modules/, /public/]
            },
            {
                test: /\.json$/,
                loader: "json-loader"
            }
        ]
    },
    target: 'node',
}

2 Answers2

4

By setting node: {fs: "empty"}, you are telling webpack that when importing fs an empty object should be returned. Remove that and it should work fine. https://webpack.js.org/configuration/node/#node

pizzarob
  • 11,711
  • 6
  • 48
  • 69
3

Instead of marking "fs" as empty, try to decorate it like this:

externals:{
    "fs": "commonjs fs"
}

That should tell webpack to load it as a module instead of considering it an environment object/ variable.

Ref: Node cannot find module "fs" when using webpack

PDG
  • 1,774
  • 1
  • 10
  • 8