Use imported js file in html in an ES6 application

Asked

Viewed 92 times

0

I am developing an application with ES6 and doing the build with Webpack. This application will be in a template that already imports jQuery via <script src...></script>.

How would I import, from this file, the jQuery to use it in my application? I have tried to use the $ of jQuery in the application but gives error:

$ is not defined

But I can’t take this import off the template because it’s shared by other applications.

In HTML I have the following code snippet:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

My Javascript:

class Products {
    constructor() {
        this.item = $('.prodcut-item')
    }
}
  • From what I understand, Jquery inside a file ES6, right? If that’s it, how are you doing? Please make it easy to help you. If possible, post how are you performing the Jquery.

  • Maybe if you show your code we can understand more than if you try to explain

  • window.jQuery should work.

1 answer

0


First, you should install jQuery via npm (or Yarn):

npm install jquery

There in the Javascript file, you do:

import $ from 'jquery';

So your final file would look like this:

import $ from 'jquery';

class Products {
  constructor() {
    this.item = $('.prodcut-item')
  }
}

Remembering that if you do what I said above, you can still keep the <script src></script> in your HTML.

  • I could not somehow use this jquery that I imported into html without having to install via npm?

  • How you are using Webpack and ES6, no.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.