Search code examples
reactjswebpackcreate-react-app

Basic issue re scoping in create-react-app / webpack


I am a relative newcomer to react, though I have created one functioning react app using create-react-app.

One of the selling points of react seems to be that you can migrate code piecemeal rather than all at once. I am now migrating an existing web app, and trying to see if I can get it to function within the create-react-app ecosystem with minimal modification; step 2 will be to react-ize it. I am stuck at step 1. (I think I have managed step 0—getting it to compile at all—although that took a long time.)

I have replaced the create-react-app index.html with my own index.html, and the create-react-app index.js with my own main js file, renamed to index.js. In the past, my main file was loaded with a <script> tag from index.html, and all its functions went into the global scope. Apparently now they are not going into the global scope.

In index.html, I have:

<button type="button" id="connectButton" class="btn btn-success" onclick="connect()">
    Log on
</button>

In index.js, I have:

function connect() { 
    ... 
}

In the past clicking the button would invoke the function, because it was in the global scope. Now, clicking on the button generates "ReferenceError: connect is not defined," because apparently it is not going into the global scope.

Someone downvoted my original version of this question, perhaps because I'm asking about something that is not "the react way of doing things." I am completely aware of that, but the way to get people to do things "the react way" is to show them a way that they can migrate their codebases incrementally. So I can't imagine I'm the only person who's had this problem. My attempts at googling didn't seem to come up with anything helpful, though.

Addendum: I see that I can work around this by inserting window.connect = connect; after the function definition, which puts it in the global scope. I will add that as an answer to this question, but maybe someone has a better explanation or workaround, in which case I will accept their answer. Thank you.


Solution

  • As I remarked in the edited version of the question, inserting window.connect = connect; after the function definition puts it in the global scope, and so seems to be an effective workaround.