Global variables in jsx file not loading

In the html file the order of the script files is 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)

      

There is code in app.js,

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

      

In the browser, app.js prints the 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 do the reverse code even though in the html file the jsx is loaded first and then the js is loaded?

And how can one declare global browsers inside a jsx file and make it available to other js / jsx files?

+3


source to share


2 answers


You must first copy the file global.jsx

to a JavaScript file, instead of relying on the transpiler function, if you want to be sure of the specific script loading behavior.

Since your file is global.jsx

not compiled until a later stage (when the JSX transpiler loads and finds all the tags script

using type="text/jsx"

), it is actually compiled and executed as JavaScript after the file app.js

has already been executed.



There are other hacky workarounds, but I would suggest pre-compiling and possibly relying on a linking system so that every JavaScript is loaded in one go (and all dependencies are loaded in the correct order).

+2


source


From what I can find on the web, the behavior is that the browser first loads the javascript files that it might need to render any responsive components. So I assume this is the expected behavior. I can confirm that the opposite is the case, i.e. by setting the abc value in js and accessing the jsx works. I couldn't find much work for this though.



While this one can be used I guess. The original goal is to lazily load heavy scripts. Ideally, I assume you will need to use the js -> jsx binding.

0


source







All Articles