简体   繁体   English

Vite在开发中如何编译JSX?

[英]How does Vite compile JSX in development?

I'm new to backend.我是后端新手。 I want to make a server serves up a React app, without using Vite (or CRA).我想让服务器提供 React 应用程序,而不使用 Vite(或 CRA)。 On front-end I'm using React, on back-end I'm using nodemon + express.在前端我使用 React,在后端我使用 nodemon + express。

I'm confused about how JSX got understood on the browser.我对浏览器如何理解 JSX 感到困惑。

This is my index.html :这是我的index.html

<body>
  <div id="root"></div>
  <script type="module" src="/src/main.jsx"></script>
</body>

When I spin up my dev server I get this error:当我启动开发服务器时出现此错误:

不允许的 MIME 类型

How come when I'm using Vite, the .jsx files are understood by the browser?为什么当我使用 Vite 时,浏览器可以理解.jsx文件? I understand Vite uses esbuild or something underneath, but I don't see any dist or build folder, and the requests seems to be directed at the .jsx files directly, not a compiled file:我知道 Vite 使用esbuild或下面的东西,但我没有看到任何distbuild文件夹,并且请求似乎直接针对.jsx文件,而不是编译文件:

请求 App.jsx

I think I'm in over my head here.我想我在这里不知所措。 How do people make a fullstack React app?人们如何制作全栈 React 应用程序?

Even though the request looks like it's fetching the JSX source, it is not.尽管请求看起来像是在获取 JSX 源代码,但实际上并非如此。 What happens is the browser asks for App.jsx , and the vite server responds with a compiled version of App.jsx .发生的事情是浏览器请求App.jsx ,而 vite 服务器以App.jsx的编译版本响应。 You can see this in action by clicking on the request and previewing the response.您可以通过单击请求并预览响应来查看实际效果。 Notice all the JSX is compiled down.注意所有的 JSX 都被编译下来了。

You won't see a build folder in dev because the compilation happens in memory in the vite server.你不会在 dev 中看到构建文件夹,因为编译发生vite 服务器中的 memory 中。 It doesn't serve them from disk, it does it on the fly.它不是从磁盘为它们提供服务,而是即时进行。

So it's kind of like a middleware.所以它有点像一个中间件。 JSX isn't really running in the browser, it just references the precompiled version that sits in vites memory using the original filename. JSX 并没有真正在浏览器中运行,它只是使用原始文件名引用 vites memory 中的预编译版本。

Why are you wanting to not use vite?你为什么不想使用 vite? Are you trying to build for production?您是否正在尝试构建生产环境? In this workflow, everything is different.在这个工作流程中,一切都不同了。 You execute a vite build and serve the built files statically from disk.您执行 vite 构建并从磁盘静态提供构建的文件。 You don't want to be doing on-the-fly compilation in production anyway.无论如何,您不想在生产中进行即时编译。

If you are wanting to add a developer mode to your server, I would recommend configuring Vite in middleware mode and bundle it with your existing server.如果你想为你的服务器添加开发者模式,我建议将 Vite 配置为中间件模式并将其与你现有的服务器捆绑在一起。

Alternatively, you could develop your UI through the vite server and configure vite to proxy through API requests to your "real" backend.或者,您可以通过 vite 服务器开发您的 UI,并将 vite 配置为通过 API 请求代理到您的“真实”后端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM