script tag text/babel variable scope

2019-02-16 12:36发布

问题:

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.

回答1:

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.