简体   繁体   English

script tag text / babel变量范围

[英]script tag text/babel variable scope

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 (ie compile the JSX to JS after every change). 首先,我理解text/babel不是用于制作,但我发现它对于开发非常有用,因为当我对我的.jsx文件进行更改时,django的dev webserver将重新加载而无需我做任何事情(即将JSX编译为每次改变后的JS)。

I am not in control of the build environment (eg django) as this is a small plugin for a larger system that I am not developing. 我不能控制构建环境(例如django),因为这是一个我不开发的大型系统的小插件。

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: mything东西在main.jsx ,简单如下:

var mything = "hello";

If main.jsx is javascript (and the type of the script tags is changed accordingly) then this will work just fine. 如果main.jsx是javascript(并且相应地更改了脚本标签的类型),那么这将正常工作。 As text/babel though, it will not work because mything is not in scope. 作为text/babel mything ,它不会起作用,因为我的mything不在范围内。

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. 我之前将所有代码都放在一个text/babel块中,但随着它的增长,将它分成几个JSX文件会很不错。

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. 如果没有深入了解Babel来源(查看https://github.com/babel/babel/blob/master/packages/babel/src/api/browser.js ),我猜它会读到你的JSX源,源上进行改造,然后eval以某种方式来执行它的来源。 The scope is not shared because babel prepends 'use strict'; 范围不共享,因为babel prepend'use 'use strict'; to the transformed code (standard in ES6). 转换后的代码(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 ). 如果你真的需要公开一个变量,你可以将它附加到window (即在你的JSX中使用window.mything而不仅仅是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. 您可以使用构建步骤通过Babel转换代码,并使用browserify / webpack来管理依赖项。

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

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