简体   繁体   中英

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM