将Babel添加到HTML [英] Adding Babel to HTML
问题描述
我是ReactJS的新手,在将babel导入html时遇到问题.目前,该项目托管在代码笔链接到代码笔上.我正在尝试在本地主机上托管项目,并且很难将babel导入到html中而不会出现错误.当我使用<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
之类的脚本标签导入babel时,项目崩溃.您能帮我弄清楚如何使用脚本标记导入babel吗?
I am new to ReactJS and I am having issues with importing babel to html. Currently the project is hosted on code pen link to code pen. I am trying host the project on local host and I am having hard time importing babel to html without an error. When I import babel using script tag like <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
the project crashes. Can you help me figure out how to import babel using script tag.
推荐答案
来自文档,选择在浏览器中"选项:
From the documentation, choosing the "in the browser" option:
安装:
您可以将 babel/babel-standalone 用作babel的预编译版本.
You can use babel/babel-standalone as a precompiled version of babel.
用法:
<div id="output"></div>
<!-- Load Babel -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- Your custom script here -->
<script type="text/babel">
const getMessage = () => "Hello World";
document.getElementById('output').innerHTML = getMessage();
</script>
创建.babelrc配置文件:
太好了!您已经配置了Babel,但实际上还没有做到
任何事物.在项目根目录中创建一个 .babelrc
配置并启用
一些插件.
Great! You've configured Babel but you haven't made it actually do
anything. Create a .babelrc
config in your project root and enable
some plugins.
首先,您可以使用 env preset
,它可以启用转换为了
ES2015 +:
To start, you can use the env preset
, which enables transforms for
ES2015+:
npm install babel-preset-env --save-dev
要启用预设,您必须在.babelrc
文件中对其进行定义,如下所示:
In order to enable the preset, you have to define it in your .babelrc
file, like this:
{ "presets": ["env"] }
请注意,以这种方式使用Babel的用例非常有限.我建议您至少使用 Babel CLI 来转换代码.或者,甚至更好的是,每次代码更改时,使用 Webpack 这样的构建工具来运行Babel.
Note that using Babel this way has a really limited use case. I'd suggest you to use at least the Babel CLI to transform your code. Or, even better, use a build tool like Webpack to run Babel each time your code changes.
此外,建议您查看创建React App .这是由React teamp构建的React应用程序初始化程序,可以为您进行所有设置(包括Babel和Webpack配置).
Also, I'd suggest you to look at Create React App. It's a React app initializer built by the React teamp that makes all the setup for you (including Babel and Webpack configurations).
这篇关于将Babel添加到HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!