Documente Academic
Documente Profesional
Documente Cultură
hackernoon.com/a-dead-simple-webpack-4-example-with-vanilla-javascript-no-libraries-and-
frameworks-8b9d0a7684be
This is a response to a Stack Overflow question. I figured out that there are people out there that may need
this, even though it may look silly, at the very beginning, learning Webpack is swimming in muddy waters.
This is a quick and dirty crash course using Webpack 4 and Vanilla JavaScript (No Libraries and
Frameworks).
Open a new folder in your computer. Check that you have NodeJS installed. Run npm init and fill in the
details. After that do:
We’re going to use Webpack in order to create an alert to the user when it clicks the “Alerts the user!”
button, and write some random text when the user clicks “Write text to the p tag”
Since we’re learning the basics, we’ll create 2 additional files: alertbox.js , and write-text.js Your
structure should look something like this:
--index.html
--src/
-—----alert-box/
-—-------------/alert-box.js
-—----write-text/
-—-------------/write-text.js
sayHi() {
alert("Hello ");
}
}
This is an ES2015/ES6 class. We can include it in our scripts by doing import {AlertBox} from
'./alert-box/alert-box';
Which this is a traditional module.exports method on how to export (pun not intended) your code from a
file.
document.addEventListener('DOMContentLoaded', () => {
const alertButton = document.getElementById('js-button');
alertButton.addEventListener('click', alertUser.sayHi);
const pTagButton = document.getElementById('js-write-text-button');
/**
* This is another variation. We create an anonymous function (Search more about it online)
* and we call the function.
*/
pTagButton.addEventListener('click', () => {
writeText(pTag)
});
});
There’s a lot going on. First of all we need to import the alert-box and write-text files into our code. We do
this by using the import statement that you see in there (require is also valid! ).
One of them is a ES2015 class (AlertBox), we need to instantiate it before we can use it, that’s why we do
const alertUser = new AlertBox();
I’m going to stop the explanation here, and encourage you to check the source code for more detailed
information. Is good practice that you do this, since there will be dark times that you will have to dig into to
find the root cause of your problem.
Then open your index.html and voila! No need to run on a Web Server. This works directly from double-
clicking the index.html file.
3/4
4/4