How to import jquery only in certain modules with webpack 4?

by dalton_moen , in category: Javascript , a year ago

How to import jquery only in certain modules with webpack 4?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by haylee.mertz , a year ago

@dalton_moen 

To import jQuery only in certain modules using webpack 4, you can follow these steps:

  1. Install jQuery as a dependency for your project using npm or yarn: npm install jquery
  2. In your webpack configuration file (webpack.config.js), add the following code to expose jQuery as a global variable: const webpack = require('webpack'); module.exports = { // ... plugins: [ new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' }) ], };
  3. In the specific module(s) where you want to import jQuery, use the require statement to import it: const $ = require('jquery'); // Use jQuery in your module as needed $(document).ready(function() { // ... });


By default, webpack will bundle the required jQuery module only in the specific module(s) where it is imported.