1

I want to include an external Javascript(with jQuery) to reactjs.

I did take a look to this, but there are still some error.

I have a external JS file, called external.js:

$(document).ready(function() {
    document.addEventListener("deviceready", onDeviceReady, 
});


function onDeviceReady() {
    console.log("The device is ready");
}

In index.html, i add the <script src="external.js"></script> to the 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>

Inside the React js project, I added the following code to App.js:

import * as jQuery from 'jquery';
window.$ = jQuery;

However, when I run the reactJS project with command npm start, inside the console, it shows

external.js:1 Uncaught ReferenceError: $ is not defined

What should I do in order to include the external js file and also the jQuery?

11
  • Are you using webpack? Commented Jan 8, 2018 at 7:17
  • I am using npm for building the React js app Commented Jan 8, 2018 at 7:26
  • So, you don't have a webpack.config file? Commented Jan 8, 2018 at 7:27
  • I don't have webpack.config file Commented Jan 8, 2018 at 7:36
  • 1
    Which one of them depends on the other one? I am guessing index.js is your root script? If so, I would like you to add a script tag, and reference to this script, and make sure that it comes before the external.js script element. Commented Jan 8, 2018 at 7:54

1 Answer 1

1

Your external script is executed before the statement window.$ = jQuery. Try to include the jQuery (before the inclusion of the external script) like you included the external script

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.