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.
Script tags are scoped to the app that created them. When an app is uninstalled from a shop, all of the script tags that it created are automatically removed along with it.
Babel is a toolchain that is mainly used to convert ECMAScript 2015+ code into a backwards compatible version of JavaScript in current and older browsers or environments.
Use it via UNPKG: https://unpkg.com/@babel/standalone/babel.min.js. This is a simple way to embed it on a webpage without having to do any other setup. Install via NPM: npm install --save @babel/standalone.
Babel is a tool that lets you write your Javascript code using all the latest syntax and features, and run it in browsers that may not support those features. Babel is a transpiler that will translate your modern JS code into an older version of Javscript that more browsers are able to understand.
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 eval
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With