简体   繁体   中英

Exporting function in ES6 / react

On the server side (nodejs/express), I have no problems in exporting and referencing this file (using Attempt1).

// collectionFile.js
function collection() {
    let data = {};
    function getData(key) {
        return data[key];
    }
    function setData(key, value) {
        data[key] = value;
    }
    return {
        getData: getData,
        setData: setData
    };
}

const instanceOfCollection = collection();

On the client side (React), I'm just not able to reference and access the getData function. Below are some of the combination I tried. None of them work. How can I make it work ?

// Attempt1: export
// module.exports.getter = instanceOfCollection.getData;

// Attempt1: import
// const getter = require('./collectionFile').getter;
// Uncaught TypeError: getter is not a function

// Attempt2: export
// export default { instanceOfCollection };

// Attempt2: import
// import instanceOfCollection from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined

// Attempt3: export
// export const instanceOfCollection = collection();

// Attempt3: import
// import { instanceOfCollection } from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined

Edit: Turns out that I was referencing File A from File B and also File B from File A earlier

There are a lot of ways to do such things:

  1. ES5 export

    module.export = instanceOfCollection

    then

    var getData = require('my_module').getData

  2. ES6 export

    export default instanceOfCollection

    then

    import { getData, setData } from 'my_module'

  3. ES6 named export

    export const setter = instanceOfCollection.setData export const getter = instanceOfCollection.getData

    then

    import { setter, getter } from 'my_module'

    or

    import * as myCollection from 'my_module' myCollection.getter() myCollection.setter()

  4. ES5 with renaming

    module.export = { getter: instanceOfCollection.getData, setter: instanceOfCollection.setData, }

    then

    const { setter, getter } = require('my_module')

    or

    const getter = require('my_module').getter const setter = require('my_module').setter

Hope some of them will work for you.

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