3

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 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

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.