Adding Libraries
Now let's rewrite the class by using the library jQuery. We will install the library in the terminal. You can use a second terminal and leave the watching terminal untouched:
1 |
|
Then we create a new file which do the same thing, but using jQuery:
src/amazing-button-jquery.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Now please run the following command in the terminal:
1 |
|
You will see a newly created subfolder named dist
in your project folder. In there you will see
the compilation result. Among other things also the file walkthough-lib.js
. The size of this file
will be round about 113 kB. This is way too much for our small class. This is because the library
jQuery was compiled into this file. To avoid this you can add the following lines into the file
webpack.externals.js
:
webpack.externals.js
1 2 3 4 5 6 7 |
|
Now run again the command npm run build
and inspect the dist
folder. You will see your
walkthough-lib.js
is shrunk to 25 kB. If you open the index.html
in this folder in a text
editor, you will find the injected library jQuery from an external file
<script src="vendor/jquery-3.6.0/dist/jquery.min.js">
.
This means that with this configuration all necessary measures have been taken to copy the jQuery file and inject the HTML file. To learn more about this easy way to externalize libraries you can read the documentation of the CodeCoupler Webpack Externals Plugin.
However, now we would like to introduce you to an even simpler method to get a library externalized. For this please remove the configuration you have done:
webpack.externals.js
1 |
|
And remove the library you have installed:
1 |
|
Now open the following website in which you will find many libraries which are already prepared to be used with the "CodeCoupler Webpack Externals Plugin": https://www.npmjs.com/org/cc-external
One of these libraries is jQuery. To install the package and include an externalization configuration automatically you just have to type the following statement in your terminal:
1 |
|
That's all! Let's try it out and compile the package again with npm run build
and inspect the
dist
folder. You will find as before a small walkthough-lib.js
and an external jQuery library.
Let's add a second container in our static HTML file in which we will start the jQuery based application:
static/index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Finally we will change the index.js
and start our new jQuery based library in the second
container:
src/index.js
1 2 3 4 5 6 7 8 9 10 11 12 |
|
In case you have canceled the server in your watching terminal you can start the watch mode with
npm start
again and you will see the running example in your browser.