我是 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/