简体   繁体   中英

Exporting imports using module.exports and ES6

I'm trying to import a function into a file and then export it from that file. This should be straightforward but for some reason I cannot get it to work.

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

The export at the bottom of index.js fails with unexpected token despite the fact that console.log(search_actions.receive_results) prints the function. So what is the proper way of doing this?

The last line of your re-export is not valid:

export search_actions.receive_results

You can't use a foo.bar reference on the right, as the export needs an unqualified name. You can reference the field within an object declaration and export that:

export default {
  search_actions: search_actions.receive_results
}

See section 15.2.3 of the spec for the export syntax. The problem you're running into is the xy part of the export, which an object or local variable will resolve.

If you were using the ES6 import as well, you could also do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM