0

I have a JS file containing this code:

module.exports = function loadMyFun() {

    function activateSite($currentItem) {
        ...
    }
  ...
}

And I want to import it into a JSX file, I tried to do it like this but I doesn't work:

import MyNav from './MyNav.js';

const top = MyNav.activateSite();

    componentDidMount () {
        var self = this;
        MyNav.activateSite($(self));
    }
...          

I get this error:

Uncaught TypeError: _MyNav.default.activateSite is not a function

Any idea how to solve this?

1
  • Are you using webpack? Commented Jul 25, 2017 at 7:58

2 Answers 2

4

activateSite is a variable that is locally scoped to the loadMyFun function.

It is not available outside the scope of loadMyFun.

It is not a property of the loadMyFun function object.

You cannot access it without rewriting the module.

e.g.

module.exports = function loadMyFun() {
};

module.exports.activeSite = function activateSite($currentItem) {
};
Sign up to request clarification or add additional context in comments.

Comments

3

If the code you provided is actually the module you are trying to load, then there are a few problems with that module.

You are exporting a constructor loadMyFun, which you are not calling/instantiating after importing it.

If you would instantiate your constructor like this const myNav = new MyNav() you would have a instance of your exported constructor.

To make your activateSite function work, you would have to assign it to the instance itself and move it out of the local scope of loadMyFunc by assigning it like this: this.activateSite = function(){...}

If you dont need any information wrapped around your activateSite function I would recommend you export an object with your functions instead of the loadMyFun approach.

//myModule.js
module.exports = {
    activateSite: function(){ ... }
}
//otherFile.js
import { activateSite } from './myModule.js' // With destructuring
activateSite()

import myModule from './myModule.js' // Without destructuring
myModule.activateSite()

2 Comments

"You are exporting a constructor loadMyFun" — It's a function. We can't tell if it is a constructor. There isn't enough code in it.
I was assuming it because he is trying to access the defined function inside. That would require this, or an object of all functions as a return value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.