问题描述
我有两个 JSX 文件(index.js 和 app.jsx)和一个 HTML 文件,我想在 index.js 中导入 app.jsx,它是 index.html 的脚本文件。我想在没有 npm 的情况下直接运行 HTML (index.html)(仅使用 LiveServer)。我该怎么做?
代码: index.html
<!DOCTYPE html>
<html>
<head>
<Meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="root"></div>
<!-- Load React. -->
<!-- Note: when deploying,replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<!-- <script src="index.js" type="text/babel"></script> -->
</body>
</html>
index.js
import App from './app'; // we are facing issue here!
ReactDOM.render(
<App />,document.getElementById('root')
);
app.jsx
var App = React.createClass({
render: function() {
return (
<div className="app">
Hello,world!
</div>
);
}
});
export default App
解决方法
首先你需要使用较新版本的 Babel:
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
然后你需要告诉它你正在处理一个模块:
<script src="index.js" type="text/babel" data-type="module"></script>
然后你需要使用正确的模块路径。浏览器无法读取文件系统以匹配没有扩展名的名称;没有文件系统,只有 HTTP。
import App from './app.jsx';
... 然后您需要配置您的服务器,以便它为 JSX 文件发送一个 Content-Type: text/babel
标头。
我还没有想出如何在 Live Server 中做到这一点。
JSX 的客户端转译很聪明,但是一旦你超越了最琐碎的情况,最终会带来更多的麻烦。你说你想避免它,但 React 设计是为了与在 Node.js 上运行的工具链一起使用。
使用 Node.js 和 Parcel 设置一个是 very easy,我建议改用这条路线。