Search code examples
javascriptnode.jswebpackcommonjs

Common js default export doesn't work when transpiling with webpack


Am using a webpack basic configuration and when i use the basic export from common js it doesn't works.

webpack.config.js

var commonJsConfig = {
  target: "node",
  mode: "production",
  output: {
    filename: "hello.node.js",
    libraryTarget: "commonjs",
  },
};

module.exports = commonJsConfig;

When i do this:

src/index.js file

function hello() {
  console.log("hello");
}

module.exports = hello;

test.js

const hello = require("./dist/hello.node");
console.log(hello);
hello();

the function hello is printed like an empty object however if i do this:

src/index.js file

function hello() {
  console.log("hello");
}

module.exports = { hello };

test.js

const hello = require("./dist/hello.node").hello;
console.log(hello);
hello();

It works just fine

I am wondering why is that, i don't get why module.exports = hello doesn't works


Solution

  • What fixed it for me was just changing the library target to commonjs-module like so:

    var commonJsConfig = {
      target: "node",
      mode: "production",
      output: {
        path: path.resolve(__dirname, "dist"),
        filename: "basic-indexer.node.js",
        libraryTarget: "commonjs-module",
      },
    };
    
    module.exports = commonJsConfig;