【问题标题】:Rollup with CommonJS module exporting an unnamed function as the module?使用 CommonJS 模块汇总导出未命名函数作为模块?
【发布时间】:2016-12-24 21:08:14
【问题描述】:

我有一个名为 inner.js 的 CommonJS 模块,它定义了一个函数,然后将该函数导出为整个模块:

// inner.js, a legacy CommonJS module
var foo = function() { return 42; };
module.exports = foo;

在 Node 中,我可以很容易地验证它的工作原理。

> var inner = require('./inner.js');
> inner() // prints 42

但这是我想从 ES6 模块中使用的遗留模块,称为 outer.js

// outer.js, an ES6 module
import * as inner from "./inner.js";
export function bar() { return inner(); }

我看到 rollup-plugin-commonjs 在这些情况下很常用,但是当 CommonJS inner.js 模块将函数作为整个模块导出时,我无法让它工作。如果在运行汇总并将结果转储到loadme.js 后,我尝试运行加载 ES6 外部模块并尝试调用内部 CommonJS 模块中最初定义的函数,我会收到错误:

> var outer = require('./loadme.js')
undefined
> outer.bar()
TypeError: inner$2 is not a function
    at Object.bar (/.../so-rollup-question/loadme.js:27:25)

我认为我只是未能正确加载 CommonJS 模块,以使模块本身作为函数运行。我对 UMD 不够熟悉,无法从检查汇总输出中获得任何有意义的信息。

这篇文章的其余部分是关于一个最小的例子。


这是我非常简单的index.js

// index.js
export {bar} from "./outer.js";

由我的汇总配置读取:

// rollup.config.js
import npm from "rollup-plugin-node-resolve";
import commonjs from 'rollup-plugin-commonjs';

export default {
  entry : "index.js",
  format : "umd",
  moduleName : "sphereModule",
  plugins : [ npm({jsnext : true}), commonjs() ],
  dest : "loadme.js"
};

我有一个complete clonable repository 来演示这个问题。

【问题讨论】:

  • 如果inner.js 只是导出函数,那你为什么要做import * as inner from "./inner.js";?你试过import inner from "./inner.js"; 吗?
  • @FelixKling 尽管我尝试了许多不同的排列组合,但在我愚昧无知的头脑中可能会有所帮助,但我并没有尝试那个非常简单和明显的组合。谢谢你。如果您愿意发布答案,我将很高兴并感激地接受它。

标签: javascript node.js ecmascript-6 commonjs rollupjs


【解决方案1】:

直接赋值给module.exports基本上相当于有一个默认导出。因此,按如下方式导入模块应该可以工作:

import inner from "./inner.js";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 2018-02-18
    • 2020-04-24
    • 2018-04-13
    • 1970-01-01
    相关资源
    最近更新 更多