简体   繁体   English

如何直接从脚本标签使用babel而不自行安装babel

[英]How to use babel directly from a script tag without installing babel itself

I'm writing react with all of these libs introduced from cdnjs.com. 我正在用从cdnjs.com引入的所有这些库编写响应。 However, I find it reporting error: 'Uncaught TypeError: Cannot read property 'keys' of undefined' even if I don't write a single line of javascript code. 但是,我发现它报告了错误:'Uncaught TypeError:无法读取未定义的属性'keys',即使我没有写一行JavaScript代码也是如此。

How could it happen? 怎么会这样

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.1.19/browser.min.js"></script>
<script text="text/babel">
//some code here

</script>

Including babel in browser is not really the way it is supposed to work. 在浏览器中包含babel并不是它应该工作的方式。

Babel is a build tool - it should be only a part of your build process. Babel是一个构建工具-它应该只是构建过程的一部分。 Most commonly, you would use a bundler like webpack or browserify, which can use babel to transpile your code from ES6 to ES5 (or other target version). 最常见的是,您将使用捆绑程序,例如webpack或browserify,它们可以使用babel将代码从ES6转换为ES5(或其他目标版本)。

Here you can see all the different ways you can include babel into your build process. 在这里,您可以看到将babel纳入构建过程的所有不同方式。

This way, all the processing happens on your machine/server and you will not need to include babel in the client, because it will receive only the transpiled code that it can understand. 这样,所有处理都在您的机器/服务器上进行,并且您将不需要在客户端中包含babel,因为它将仅接收它可以理解的已编译代码。

However, it is possible to transform your code directly in the browser using babel-standalone . 但是,可以使用babel-standalone在浏览器中直接转换代码。 You can see it working here . 您可以看到它在这里工作。

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.7.7/babel.min.js"></script>
<script text="text/babel">
var input = 'const getMessage = () => "Hello World";';
var output = Babel.transform(input, { presets: ['es2015'] }).code;
console.log(output);
</script>

However you should almost never need to use this approach. 但是,您几乎永远不需要使用这种方法。

You can use babel standalone for this Link 您可以将此链接独立使用babel

<script src="https://unpkg.com/babel-standalone@6.26.0/babel.js"></script>


<script type="text/babel">
 //your code
</script>

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

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