[英]Adding react to existing web page (legacy) - imports not working
I have imported react dev to a webpage (legacy HTML+JQuery) as follows:我已将 react dev 导入网页(旧版 HTML+JQuery),如下所示:
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script type="module" src="dist/Menu.js"></script>
and I'm trying to use the Menu component, which has the following code:我正在尝试使用具有以下代码的 Menu 组件:
import menuData from "./menuData";
import MenuItem from "./MenuItem";
export const Menu = () => {
return (
<p>Some code..</p>
)
};
let domContainer = document.querySelector('#main_menu');
ReactDOM.render(<Menu />, domContainer);
In my legacy app, before importing I had to transpile the JSX to JS using: npx babel --watch src --out-dir dist --presets react-app/prod
,在我的遗留应用程序中,在导入之前,我必须使用
npx babel --watch src --out-dir dist --presets react-app/prod
将 JSX 转换为 JS,
And in my legacy app, in addition to the imports (above), I wrote the following element:在我的遗留应用程序中,除了导入(上图)之外,我还编写了以下元素:
<div id="main_menu"></div>
but my legacy app shows an 404 Error for my imports:但我的旧版应用程序对我的导入显示 404 错误:
404 https://mywebpage.com/dist/menuData
404 https://mywebpage.com/dist/MenuItem
Any idea what I'm missing?知道我错过了什么吗? How I can start using React components (with imports of another components) in my legacy HTML+JQuery app?
如何在我的旧版 HTML+JQuery 应用程序中开始使用 React 组件(导入其他组件)?
Do the imported paths really exist on your site?导入的路径是否真的存在于您的网站上? Open a browser and go to
打开浏览器和 go 到
https://mywebpage.com/dist/menuData
If they don't resolve to plain .js
source code - which it sounds like they don't - they won't work.如果他们不解析为普通的
.js
源代码——听起来他们没有——他们将无法工作。 You probably need to add the file extension, since it sounds like your server isn't doing it:您可能需要添加文件扩展名,因为听起来您的服务器没有这样做:
import menuData from "./menuData.js";
import MenuItem from "./MenuItem.js";
such that going to这样去
https://mywebpage.com/dist/menuData.js
shows you the JS file.向您展示 JS 文件。
But an even better option you might also consider would be to bundle the code together during a build process, so that only one .js
file has to be served to the client.但您可能还会考虑一个更好的选择,即在构建过程中将代码捆绑在一起,这样只需将一个
.js
文件提供给客户端。 As an app grows larger and larger, if the client has to request 20 or 30 or more modules from your server, that can be a significant performance hit if you aren't using HTTP/2.随着应用程序变得越来越大,如果客户端必须从您的服务器请求 20 个或 30 个或更多模块,如果您不使用 HTTP/2,这可能会严重影响性能。 Consider a module bundler like Webpack.
考虑一个像 Webpack 这样的模块捆绑器。 You may be able to turn your HTML into
您可以将 HTML 变成
<script src="dist/bundle.js"></script>
by bundling all of your modules (and React, and any other libraries you happen to be using here) together into a single file.通过将所有模块(和 React,以及您碰巧在这里使用的任何其他库)捆绑到一个文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.