Saravana Kumar
Saravana Kumar

Reputation: 394

Global variables in jsx file are not loaded

In html file, the order of script files are included as jsx files and then js files as,

<script src="global.jsx" type="text/jsx"></script>
<script src="app.js" type="text/javascript"></script>

In global.jsx, the code is,

var abc = {ab: 1, ba: 2}
console.log("from jsx file " + abc)

In app.js, the code is,

console.log("from js file " + abc)

In browser app.js prints error, then global.jsx prints the variable value as:::

app.js -----> ReferenceError: abc is not defined
global.jsx -----> from jsx file [Object object]

How does the browser run the code in reverse, even though in html file, jsx is loaded first and then js is loaded?

And how can one declare browser globals inside jsx file and make it available for other js/jsx files?

Upvotes: 3

Views: 1606

Answers (2)

WiredPrairie
WiredPrairie

Reputation: 59763

You should precompile your file, global.jsx into a JavaScript file rather than relying on the transpiler feature if you want to be assured of a particular script loading behavior.

As your global.jsx file isn't compiled until a later step (when the JSX transpiler loads and finds all script tags with type="text/jsx"), it's actually being compiled and executed as JavaScript after the app.js file has already executed.

There are other somewhat hacky workarounds, but I'd suggest precompilation and possibly relying on a bundling system so that all of the JavaScript is loaded at one time (and all of the dependencies will be loaded in the correct order).

Upvotes: 2

Bharath M.S
Bharath M.S

Reputation: 31

From what I can find on the internet the behavior is that browser loads the javascript files first that may be required for rendering any react components. So I guess that is an expected behavior. I can confirm that the reverse i.e., setting the value of abc in js and accessing from jsx works. I could not find many work arounds for this though.

Although this can be used I am guessing. The original purpose is to load heavy scripts lazily. Ideally I guess you would have to use js -> jsx binding.

Upvotes: 0

Related Questions