【发布时间】: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