【问题标题】:Common js default export doesn't work when transpiling with webpack使用 webpack 转译时,常见的 js 默认导出不起作用
【发布时间】:2020-06-10 14:30:37
【问题描述】:

我正在使用 webpack 基本配置,当我使用普通 js 的基本导出时,它不起作用。

webpack.config.js

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

module.exports = commonJsConfig;

当我这样做时:

src/index.js 文件

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

module.exports = hello;

test.js

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

函数 hello 像一个空对象一样打印但是如果我这样做:

src/index.js 文件

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

module.exports = { hello };

test.js

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

效果很好

我想知道为什么会这样,我不明白为什么 module.exports = hello 不起作用

【问题讨论】:

    标签: javascript node.js webpack commonjs


    【解决方案1】:

    为我解决的问题只是将库目标更改为 commonjs-module,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 1970-01-01
      • 2017-08-31
      • 2021-07-02
      • 2017-11-12
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 2017-11-05
      相关资源
      最近更新 更多