Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  52] [ 4]  / answers: 1 / hits: 22754  / 9 Years ago, tue, october 13, 2015, 12:00:00

Firstly, I understand text/babel is not for use in production, but I found it quite useful for development as when I make a change to my .jsx file django's dev webserver will reload without me having to do anything (i.e. compile the JSX to JS after every change).



I am not in control of the build environment (e.g. django) as this is a small plugin for a larger system that I am not developing.



The problem is this:



<script type=text/babel src={% static myapp/js/main.jsx %}></script>

<script>
$(function() {
console.log(mything);
}
</script>


Where mything is in main.jsx, something as simple as:



var mything = hello;


If main.jsx is javascript (and the type of the script tags is changed accordingly) then this will work just fine. As text/babel though, it will not work because mything is not in scope.



Uncaught ReferenceError: mything is not defined


This makes sense to me as I wouldn't expect script tags of different types to share a scope, but I'm wondering if there is some clever way around this to aid development?



I previously had all the code in a single text/babel block, but as it grows, it would be nice to separate it out into several JSX files.


More From » babeljs

 Answers
17

Without diving too deeply into the Babel source (looking at https://github.com/babel/babel/blob/master/packages/babel/src/api/browser.js), I'm going to guess that it reads your JSX source, performs transformation on the source, and then evals the source in some way to execute it. The scope is not shared because babel prepends 'use strict'; to the transformed code (standard in ES6).



If you really need to expose a variable, you can attach it to window (ie use window.mything in your JSX instead of just mything). Ideally, you should make use of modules as you split your code up into multiple files. You can make use of a build step to transform your code through Babel and use browserify/webpack to manage dependencies.


[#64754] Friday, October 9, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;