2016-08-18 86 views
0

我有一個CommonJS的模塊,稱爲inner.js,其定義了一個函數,然後作爲整個模塊起作用的出口:與CommonJS模塊彙總導出一個未命名的功能作爲模塊?

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

在節點,我可以容易地驗證此工作原樣。

> 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證明的問題。

+2

爲什麼要那樣做,從「./inner.js」'進口*爲內;如果''inner.js'僅導出功能?你試過從「./inner.js」導入內部嗎? –

+0

@FelixKling雖然我嘗試了很多不同的東西排列組合,對我的無知的無知者來說,可能有幫助,但我沒有嘗試這種簡單明瞭的方法。謝謝。如果您想發表一個答案,我會很樂意並且感激地接受它。 –

回答

3

直接分配給module.exports基本上等同於具有默認導出。因此,導入模塊如下應該工作:

import inner from "./inner.js";