rkhan
rkhan

Reputation: 315

how to export a constant which is inside a function? - ReactJS

In a file called File_A.js I have a function that contains a constant. I want to export this const, and only this one (not the whole function) in order to use the constant's value in another file called File_B.js. I tried to use module.exports but it returns that the variable is undefined. Below a simplified example. Thanks

// my function in File_A.js
const MyFunctionA = () => {

  const myVariable = 'hello'
  module.export = {myVariable: myVariable}

  return (
  /*...*/
  );
}

// my second function in File_B.js
const MyFunctionB = () => {

  const {myVariable} = require('./File_A.js');
  console.log(myVariable) // undefined

  return(
  /*...*/
  );
}

Upvotes: 1

Views: 9004

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075915

how to export a constant which is inside a function?

There are two answers to this:

  1. You don't. It doesn't make sense. Instead, you move the constant out of the function and export it.

  2. You do it exactly as you have done, but the constant won't be in the module's exports until MyFunctionA has been executed at least once. This is possible because the CommonJS-style modules that you're using are dynamic and can change at runtime. However, making your exports dependent on a function call is asking for trouble, as you've discovered.

So taking #1 on board, we get:

// my function in File_A.js
const myVariable = "hello"; // Odd name for a constant? ;-)
module.exports.myVariable = myVariable;
const MyFunctionA = () => {
    return (
        /*...*/
    );
};

A couple of notes on that:

  1. MyFunctionA still closes over the constant and references it exactly the way it used to.

  2. myVariable doesn't become a global, because the top-level scope of a CommonJS module isn't global scope.

Upvotes: 3

Related Questions