K
K
Kirill Karpik2019-08-21 14:50:21
JavaScript
Kirill Karpik, 2019-08-21 14:50:21

How to setup jquery in webpack?

Hello. New to webpack. I don't want to connect jquery through a file, since it is used on all pages, so I left this option as a last resort. I've tried every jquery connection I've seen. Installed jquery via npm

npm install jquery --save-dev

Tried
module.exports = {
  //...
  module: {
    rules: {[
    //...
    {
      test: require.resolve('jquery'),
      use: [{
        loader: 'expose-loader',
        options: 'jQuery'
      }, {
        loader: 'expose-loader',
        options: '$'
      }]
    }]
  }
}

So
module.exports = {
  //...
  plugins: [
    //...
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery",
      "window.$": "jquery"
    })
  ]
}

In both cases and separately in the entry file I tried
  • import "jquery";
  • import $from "jquery";
  • require("jquery");

together with
window.$ = $;
window.jQuery = $;

but jquery works strangely and when calling the $ function, it returns a dom node instead of a jquery object, which is why click and other functions do not work. What is the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexhovansky, 2019-08-22
@alexhovansky

1) When installing, you need to specify the --save flag; with --save-dev, jQuery will not get into the production assembly;
2) ProvidePlugin is needed just so that it is not necessary to write import in each file. $: "jquery" is the same as every js file will have import $;
3-4 weeks ago I used jQuery, no dancing with a tambourine was needed, just npm i --save jquery, then just import $ from 'jquery'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question