我正在尝试将函数导入到文件中,然后从该文件中导出。这应该很简单,但由于某种原因我无法让它工作。
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
尽管 console.log(search_actions.receive_results) 打印了该函数,但 index.js 底部的导出失败并出现意外标记。那么这样做的正确方法是什么?
最佳答案
重新导出的最后一行无效:
export search_actions.receive_results
您不能在右侧使用 foo.bar
引用,因为导出需要非限定名称。您可以在对象声明中引用该字段并将其导出:
export default {
search_actions: search_actions.receive_results
}
参见section 15.2.3导出语法的规范。您遇到的问题是导出的 x.y
部分,对象或局部变量将解决该问题。
如果您也使用 ES6 import
,您也可以这样做:
import {receive_results} from 'search_actions';
export default receive_results;
关于javascript - 使用 module.exports 和 ES6 导出导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36458004/