Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

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>
like image 418
Chang Avatar asked May 14 '16 15:05

Chang


1 Answers

Including babel in browser is not really the way it is supposed to work.

Babel is a build tool - it should be only a part of your build process. 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).

Here you can see all the different ways you can include babel into your build process.

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.

However, it is possible to transform your code directly in the browser using 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.

like image 177
Július Retzer Avatar answered Oct 30 '22 17:10

Július Retzer