I'm developing a ReactJS application using Babel/JSX syntax. I want to write an module made of React's components. But I cannot use objects of a babel script inside a Javascript the same way I could use objects of a Javascript inside another Javascript.
Html:
<script src="/js/react_babel_jsx.js" type="text/babel" ></script>
<script src="/js/my_javascript.js"></script>
/js/react_babel_jsx.js:
var Test = function(){
this.hello = function () {
console.log('Hello!')
}
}
/js/my_javascript.js
new Test().hello()
Console output in Chrome:
my_javascript.js:3 Uncaught ReferenceError: Test is not defined
How could I use Babel script's objects inside a Javascript?
Variables defined in the Babel script are wrapped in their own closure space. It's the same as this:
function BabelStuff () {
var Test = function () {}
}
function OtherStuff () {
var x = new Test() // Test not defined!
}
If you're just wanting to get past this problem right now you can add things to the window
namespace.
window.Test = function(){
this.hello = function () {
console.log('Hello!')
}
}
But this should only be for testing, not production applications. When you're ready to move on you'll want to transpile your code ahead of time. Here's a common boilerplate that can get you started https://github.com/gaearon/react-hot-boilerplate