使用module.exports和ES6导出导入

我试图将一个函数导入到一个文件,然后从该文件中导出。 这应该是直接的,但由于某种原因,我不能得到它的工作。

search_action.js

function search_actions() { this.receive_results = function() { return { type: 'RECEIVE_RESULTS', results: results } } } module.exports = search_actions 

index.js

 require('es6-promise').polyfill(); var SearchActions = require('./search_actions.js') var search_actions = new SearchActions() //console.log(search_actions.receive_results) export search_actions.receive_results 

尽pipeconsole.log(search_actions.receive_results)打印了该函数,但index.js底部的导出仍会失败并出现意外令牌。 那么这样做的正确方法是什么?

您的再出口的最后一行是无效的:

 export search_actions.receive_results 

您不能在右侧使用foo.bar引用,因为导出需要一个非限定名称。 您可以在对象声明中引用该字段并导出:

 export default { search_actions: search_actions.receive_results } 

有关导出语法,请参阅规范的第15.2.3节 。 您遇到的问题是导出的xy部分,对象或本地variables将parsing该部分。

如果你也使用ES6 import ,你也可以这样做:

 import {receive_results} from 'search_actions'; export default receive_results;