Reputation: 5503
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
Upvotes: 1
Views: 7679
Reputation: 7973
There are a lot of ways to do such things:
ES5 export
module.export = instanceOfCollection
then
var getData = require('my_module').getData
ES6 export
export default instanceOfCollection
then
import { getData, setData } from 'my_module'
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()
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.
Upvotes: 8