我想在 reactjs 中包含一个外部 Javascript(带有 jQuery)。
我确实看过this , 但仍然存在一些错误。
我有一个外部 JS 文件,名为 external.js:
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady,
});
function onDeviceReady() {
console.log("The device is ready");
}
在 index.html 中,我添加了 <script src="external.js"></script>
到脚本:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<script src="external.js"></script>
<div id="root"></div>
</body>
</html>
在 React js 项目中,我将以下代码添加到 App.js:
import * as jQuery from 'jquery';
window.$ = jQuery;
但是,当我使用命令 npm start
运行 reactJS 项目时, 在控制台内,它显示
external.js:1 Uncaught ReferenceError: $ is not defined
我应该怎么做才能包含外部 js 文件以及 jQuery?
最佳答案
您的外部脚本在语句 window.$ = jQuery
之前执行。尝试像包含外部脚本一样包含 jQuery(在包含外部脚本之前)
关于javascript - 使用 jQuery 将外部脚本导入 React JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48145656/