Webpack is a open-source bundler for web assets like CSS or JavaScript files
To install Webpack you will need NPM to be installed on your computer or any similar package manager like Yarn.
Open a command line and go to the root directory of your project, then run
Proceed to install CLI
Now create a package.json file in the root of your project directory with the following contents
package.json
1 2 3 4 5 6 |
{ "scripts": { "build": "webpack -p", "watch": "webpack --watch" } } |
Create also a webpack.config.js file in the root of your project directory with the following contents
webpack.config.js
1 2 3 4 5 6 7 8 9 |
var path = require('path'); module.exports = { entry: './assets/js/index.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } }; |
Create a new folder named assets and a new folder named js in the assets folder with the following Javascript file
index.js
1 2 3 |
function alertButton(){ alert('Everything works fine!'); } |
Create a HTML File which we will use later to see if everything works fine
1 2 3 4 5 6 7 8 9 10 11 |
<html lang="en"> <head> <meta http-equiv='Content-Type' content='text/html; charset=utf-8'> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Webpack</title> <script src="./dist/bundle.js"></script> </head> <body class="homepage"> <button type="button" onclick="alertButton();">Click me</button> </body> </html> |
Open a command line and go to the root directory of your project, then run:
Run also:
for Webpack to create a new bundle everytime changes are made to the JavaScript file
Finnaly click the Click me button and an alert box should be displayed if everything is working fine