使用jQuery将外部脚本导入React JS

时间:2018-01-08 07:04:11

标签: javascript jquery reactjs cordova

我想将一个外部Javascript(带有jQuery)包含在reactjs中。

我确实看了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未捕获的ReferenceError:$未定义

我应该怎么做才能包含外部js文件和jQuery?

1 个答案:

答案 0 :(得分:1)

您的外部脚本在语句window.$ = jQuery之前执行。尝试包含jQuery(在包含外部脚本之前),就像包含外部脚本

一样
相关问题