Ad

Loading And Connecting Js/jsx Files

- 1 answer

I'm learning ReactJS and everything works fine when it's in one file.

I'm loading it like this <script type="text/babel" src="js/test.js"></script> because if I use type "text/javascript" the browser can't read the jsx eventhough I've seen examples with that type that work.

The problem comes when I split up the functions and variables in different files.

Let's say I have file1.js (pure js), file2.js , file3.js (jsx) that I load like this

<script type="text/javascript" src="js/file1.js"></script>
<script type="text/babel" src="js/file2.js"></script>
<script type="text/babel" src="js/file3.js"></script>

Everything in file1 loads normally.

If I invoke something in file2/file3 that is from file1 it works.

But the other way around or between file2 and file 3 there is no connection at all.

If I have var a = 10; in file2 it is undefined in file1 or file3.

Same for var a = 10; in file3.

If I have console.log("I'm going through file2"); after the variable initialization it does print in the console but the variable is still undefined in file1 and file3.

I tried putting the loading script tags on different places, tried different composition but still it doesn't work.

I'm guessing it's a problem with the "translation" that babel makes but if I try to load the file as a normal js I get the Unexpected token < syntax error.

What is the right way to connect multiple jsx files?

P.S. Everything is tested on $(document).ready() event.

Ad

Answer

Once you get beyond playing with one file it is best to start using build tools like webpack or browserify. Here are starter projects using webpack. ReactPatterns

Ad
source: stackoverflow.com
Ad