How to use jquery in a webpack?

by aniya.jaskolski , in category: Javascript , 2 months ago

How to use jquery in a webpack?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 2 months ago

@aniya.jaskolski 

To use jQuery in a webpack project, you can follow these steps:

  1. Install jQuery as a dependency in your project by running the following command in your terminal:
1
npm install jquery --save


  1. Install the webpack plugin to provide jQuery as a global variable to be used in your project by running the following command:
1
npm install webpack --save


  1. In your webpack configuration file (usually named webpack.config.js), add the following code to expose jQuery as a global variable:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const webpack = require('webpack');

module.exports = {
  // other webpack configuration options
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
};


  1. Now you can use jQuery in your project by simply importing it at the top of your JavaScript file like this:
1
2
3
import $ from 'jquery';

// Your jQuery code here


  1. Make sure to run webpack to bundle your project with jQuery included:
1
webpack


Now jQuery is set up and ready to be used in your webpack project.