Starting with Webpack
Webpack is used to bundle the input files with dependencies and generate static files using those modules.
For creating a sample webpack project, first you have to install webpack —
npm install webpack -g
Now create a sample webpack project with the following project structure
./
— — src
— — — — — — — — components
— — — — — — — — — — — — — — — — —header -> header.js
— — — — — — — — — — — — — — — — —footer ->footer.js
— — — — — — — — — — — — — — — — —maincontent -> maincontent.js
— — — — — — — — — — — — — — — — — sidebar -> sidebar.js
— — — — — — — — app.js
— — webpack.config.js
Now in maincontent.js is the file in which we will use header, footer and sidebar.
maincontent.js file will be used in app.js
Each of the files namely, header.js, footer.js, sidebar.js will contain
console.log(“This is header, footer, sidebar etc”);
In maincontent.js we will require header.js, footer.js, sidebar.js
require("../header/header.js")
require("../sidebar/sidebar.js")
require("../footer/footer.js")
In app.js, we will require maincontent.js
require(“./components/maincontent/maincontent.js”)
Now comes the backbone of the application i.e. webpack.config.js file
var path = require(‘path’);
module.exports = {
entry: ‘./src/app.js’,
output: {
//path: ‘./static/build’, /**Old code**/
path: path.resolve(‘./static/build’), /*New code*/
filename: ‘bundle.js’
},
resolve: {
// Old code
// root:[
// path.resolve(‘./src’)
// ]
// New code
modules: [
path.resolve(‘./src’)
]
}
}
In webpack.config.js, we need the input file(app.js) which we have to bundle. So, we mention it in the entry attribute. And the path of the output bundled file(bundle.js) should also be specified which contains the whole project.
Get Shivam Gupta’s stories in your inbox
Join Medium for free to get updates from this writer.
Now to run the project, open the project directory in the terminal. Then, type
webpack
After the project is compiled, you can see weboack has bundled the bundle.js files. Now, you just have to create a index.html file in the project and add a script tag which will load bundle.js file.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
<script src=”./build/bundle.js”></script>
<title>Document</title>
</head>
<body>
</body>
</html>
Now open the index.html in the browser and open the web console. You will be able to see the contents of app.js.
For each and every change in the project you will have to run the webpack command from the terminal again and again which is a very tedious task.
So, webpack comes with a facility that automates this task. You just need to type this in terminal.
webpack — check
And you are done.




