Webpack from A to Asia: Webpack import jQuery

Tram Ho

Webpack from A to Asia with kentrung

Today’s article I will guide you how to load jQuery into webpack in module load style. If in the old days we had to load jQuery into the web page this way

Now with webpack, we don’t do that because it doesn’t suit the trend ^^. Let’s find out how to do it!

1. Prepare the file

Code file original webpack.config.js :

File dist/index.html as follows:

We have two files src/a.js and src/b.js Code two js files as follows:

The jQuery code above works to find the h1 tag and add a little css in it is also quite simple.

Have not fixed the error, but keep running webpack to see how the results are npm run dev

Open the file dist/index.html and see the h1 tag without adding css, open the log to see the error

2. Load jQuery for each file

First I have to install jQuery via npm

In this case, we only need the src/a.js file to load jQuery and the other does not. We just need to add jQuery to the correct file.

Rerun webpack and we have the following log:

So in the src/a.js file, I ran the delicious jQuery code but the src/b.js file did not. Still the way above, the file needs to call jQuery is finished.

Rerun webpack and as a result no more errors, css was added successfully.

3. Webpack Provide Plugin

With the way on any file need to call jQuery in, quite a lot of writing. We have a second way to provide a webpack plugin to dynamically load jQuery, we just need to point both variables that it displays to the respective button module:

Now the two js files keep jQuery code rumbling without having to import anything

Now run webpack again: npm run dev and as a result, css has been added correctly as desired. That’s it, we no longer have to manually load jQuery as before, we all have webpack to take care of you just code ^^!

This article is over, hopefully with this article you have added a lot of useful knowledge. See you in the next article!

Share the news now

Source : Viblo