javascript - 将 Babel 添加到 HTML

标签 javascript html reactjs build babeljs

我是 ReactJS 的新手,我在将 babel 导入 html 时遇到问题。目前项目托管在码笔link to code pen .我正在尝试在本地主机上托管该项目,但我很难将 babel 导入 html 而不会出现错误。当我使用像 <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script> 这样的脚本标签导入 babel 时项目崩溃了。你能帮我弄清楚如何使用脚本标签导入 babel 吗。

最佳答案

来自documentation ,选择“在浏览器中”选项:

Installation:

You can use babel/babel-standalone as a precompiled version of babel.

Usage:

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

Create .babelrc configuration file:

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.

To start, you can use the env preset, which enables transforms for ES2015+:

npm install babel-preset-env --save-dev

In order to enable the preset, you have to define it in your .babelrc file, like this:

{ "presets": ["env"] }

请注意,以这种方式使用 Babel 的用例非常有限。我建议您至少使用 Babel CLI转换您的代码。或者,更好的是,使用像 Webpack 这样的构建工具每次代码更改时运行 Babel。

此外,我建议您查看 Create React App 。这是一个由 React 团队构建的 React 应用程序初始化程序,可以为您进行所有设置(包括 Babel 和 Webpack 配置)。

关于javascript - 将 Babel 添加到 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48414348/

相关文章:

jquery - 将鼠标悬停在父 Bootstrap 上时,会显示导航栏中的子菜单下拉菜单

html - 如何在移动 safari 上存储和播放 mp3?

html - 让列在 3 列 CSS 布局中扩展到相同的高度?

reactjs - 如何处理react中的404

javascript - 刷新后 React-Redux 状态丢失

javascript - react Js : Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

javascript - 尝试让ajax将其最后的数据与最新的数据进行比较,但它不起作用

javascript - 如何使用内部对象函数 Javascript 访问外部对象属性

javascript - 设置 cookie 无法按预期工作

javascript - 网站更改正在缓存,不会为客户更新