React.js How to pass a variable from another js file that does not have export

Viewed 1514

I have an autogenerated fairly large js file that its content is just one big variable like this:

ConstDef.js:
var ConstantDefinitions = {
variable1: "blahbalhbalh",
variable2: "blahBlahBlah",
...
variable10000: "BlahbluuBleh"
}

How can I access the contents of this file in React.js? If I add export {ConstantDefinitions} manually at the bottom of ConstDef.js, I can easily write something like:

import { ConstantDefinitions } from './ConstDef';

const defHelper = {
  getStringByKey(key) {
    const def = ConstantDefinitions [key];
    return def;
  }
};

export default defHelper ;

My plan B is to write a script to somehow append export {ConstantDefinitions} to my autogenerated file, However, I am trying to access that object without manipulating the source.

2 Answers

You could generate a Json File instead of a JS Object, and import it from React Component

I think the best method is to add export to your generator.

But as you have var variable in your file you can choice completely wrong(but workable) path. You can access to your variable because it stored in global scope. https://www.javatpoint.com/javascript-global-variable

import './youPathToVariable';
...
window.ConstantDefinitions
...

Also(as @Umberto mentioned in his answer) you can generate json file)

Related