我正在尝试从 CDN 加载 React 组件,但在加载过程中,我收到“React 未定义”错误:
备注:
更多信息:
<script crossorigin src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
"@babel/preset-env",
["@babel/preset-react", {"runtime": "automatic"}]
配置 Webpack 以使用项目的 React 作为 CDN 的外部 React 的正确方法是什么?
我设法通过添加以下内容来展示我的组件: 窗口.React = React; window.ReactDOM = ReactDOM; 但这会导致奇怪的 UI 行为,而且这对于生产代码来说也不是一个足够好的解决方案。
##### 编辑#####
这是索引文件的示例,其中我尝试提供 CDN React 和 ReactDOM:
<!DOCTYPE html>
<html>
<head>
<!-- this is my try to add react & react dom but this is giving me multiple react instances error -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react.development.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/react-dom.development.js"></script>
</head>
<body>
....
</body>
</html>
这是我的组件的示例:
import React from "react";
import { MyComponent } from "@sci/my-cdn";
const MeetingRecapSpeakersContainer = () => {
return (
<div>
<h1>Meeting Recap Speakers Container</h1>
<MyComponent />
</div>
);
};
export default MeetingRecapSpeakersContainer;
{
"name": "@msteams/components-meeting-recap-speakers",
"version": "1.0.0",
"description": "Meeting Recap Speakers Component",
"main": "index.ts",
"module": "index.ts",
"private": false,
"sideEffects": false,
"license": "UNLICENSED",
"scripts": {
"build": "node ../../../tools/build/cli/transpile.js",
"lint": "node ../../../tools/build/cli/run-package-eslint.js",
"test": "node ../../../tools/build/cli/run-package-unit-tests.js"
},
"dependencies": {
...
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-is": "^17.0.2",
"@sci/my-cdn": "1.20230828.1", // This is my CDN
"@microsoft/teams-js": "^2.11.0"
},
}
看来 React 已经是项目依赖项了:
{
"name": "@msteams/components-meeting-recap-speakers",
"version": "1.0.0",
"description": "Meeting Recap Speakers Component",
"main": "index.ts",
"module": "index.ts",
"private": false,
"sideEffects": false,
"license": "UNLICENSED",
"scripts": {
"build": "node ../../../tools/build/cli/transpile.js",
"lint": "node ../../../tools/build/cli/run-package-eslint.js",
"test": "node ../../../tools/build/cli/run-package-unit-tests.js"
},
"dependencies": {
...
"react": "^17.0.2", // <-- project dependency!
"react-dom": "^17.0.2", // <-- project dependency!
"react-is": "^17.0.2",
"@sci/my-cdn": "1.20230828.1", // This is my CDN
"@microsoft/teams-js": "^2.11.0"
},
}
根本没有理由通过 CDN 引入第二个 React 实例。删除index.html文件中的脚本。
<!DOCTYPE html>
<html>
<head>
<!-- remove react & react dom scripts -->
....
</head>
<body>
....
</body>
</html>