Getting started guide with Webpack

Webpack (https://ankitkamboj18.medium.com/)

What is Webpack?

Webpack is a module bundler. It takes the code you write and bundles it. But Webpack can also transpile, combine, and minify your code. It allows for code splitting, in which the client can load blocks of code on demand rather than having to send one huge file to the client. Webpack is also compatible with React.js.

Why Webpack?

Using a module bundler like Webpack solves a lot of problems. Loading individual javascript files in an application will trigger multiple calls to the server. Processing each of those requests and sending the resources to the client takes time. The bigger the application, the longer the time, Thus, having lots of files and requests is simply bad UX.

Installing Webpack

Webpack is available as a Node package. To install Webpack:

 npm install -g webpack

CLI (Command Line Interface)

Now that we have access to the webpack command, we can create two files: app.js and index.html.

console.log("Loading...");document.write("Well, hello there Webpack!!!!");
<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting started with Webpack: Part 1</title>
</head>
<body>
<script src="bundle.js"></script>
</body>
</html>
webpack ./app.js bundle.js
webpack ./app.js bundle.js --watch
webpack ./app.js bundle.js -p

webpack.config.js

Obviously, typing out the command in the terminal is not practical. Moreover, when you have multiple operations you want to perform — compile LESS/Sass files to CSS, CoffeeScript to Javascript and transpile ES6 to ES5, it’s better to configure webpack to take care of the operations for us. This is where the webpack.config.js file comes in.

npm install style-loader css-loader babel-loader babel-core babel-preset-es2015 --save-dev
module.exports = {
entry: ['./app.js'],
output: {
path: __dirname,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
loaders: ['babel'],
query: {
presets: ['es2015']
}
},
{
test: /\.css$/,
loaders: ['style-loader!css-loader']
}
]
}
}

entry

The entry property lets you define the top level file(s) that we want to include in the bundle.

output

The output object let's you define the output configuration. The path property defines the path to the root of the project. The filename property defines the name of the output file.

module loaders

The loaders array contains the configurations for each loader module.

npm install webpack-dev-server -g
webpack-dev-server

Software Developer