简体   繁体   English

加载和连接js / jsx文件

[英]Loading and Connecting js/jsx files

I'm learning ReactJS and everything works fine when it's in one file. 我正在学习ReactJS,当它在一个文件中时,一切工作正常。

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. 我像这样<script type="text/babel" src="js/test.js"></script>一样加载它,因为如果我使用"text/javascript"类型,尽管浏览器无法读取jsx看到了具有这种功能的示例。

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 假设我有这样加载的file1.js(纯js),file2.js和file3.js(jsx)

<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. file1中的所有内容均正常加载。

If I invoke something in file2/file3 that is from file1 it works. 如果我在file2 / file3中调用来自file1的内容,它将起作用。

But the other way around or between file2 and file 3 there is no connection at all. 但是相反,在文件2和文件3之间或之间根本没有连接。

If I have var a = 10; 如果我有var a = 10; in file2 it is undefined in file1 or file3. 在file2中,在file1或file3中未定义。

Same for var a = 10; var a = 10;相同var a = 10; in file3. 在文件3。

If I have console.log("I'm going through file2"); 如果我有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. 变量初始化后,它确实会在控制台中打印,但在file1和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. 我猜测这是babel进行的“翻译”问题,但是如果我尝试以普通js的形式加载文件,则会出现Unexpected token <语法错误。

What is the right way to connect multiple jsx files? 连接多个jsx文件的正确方法是什么?

PS Everything is tested on $(document).ready() event. PS一切都在$(document).ready()事件上进行了测试。

Once you get beyond playing with one file it is best to start using build tools like webpack or browserify. 一旦您不再使用一个文件,那么最好开始使用诸如webpack或browserify之类的构建工具。 Here are starter projects using webpack. 这是使用webpack的入门项目。 ReactPatterns ReactPatterns

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM