webpack is a powerful module bundler and it becomes an essential part of our JavaScript Ecosystem. This ppt comprises an overview on webpack, some of the core concepts of webpack and it's configurations with some working examples.
5. Entry Point
● Defines a module for webpack to
begin with.
● Generates Dependency graph.
● Figure out Entry point’s dependencies.
● By default, ./src/index.js
module.exports = {
entry: './path/to/my/entry/file.js'
};
webpack.config.js
5
6. Output
webpack.config.js
● Defines where to emit the created bundles.
const path = require('path');
module.exports = {
entry: './path/to/my/entry/file.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'my-first-webpack.bundle.js'
}
};
6
7. Loaders
● Webpack Understands JS & JSON files.
● Loaders allow webpack to process other
files.
● Two props:
○ Test - Identifies file to be transformed.
○ Use - Indicates loaders to be used.
const path = require('path');
module.exports = {
output: {
filename: 'my-first-webpack.bundle.js'
},
module: {
rules: [{
test: /.txt$/,
use: 'raw-loader'
}]
}
};
webpack.config.js
7
8. Plugin
● Bundle optimization
● Asset Management
● Injection of env variables.
● Customizable through options.
○ require() a plugin to use it.
○ Create an instance of the plugin with
new operator
const HtmlWebpackPlugin =
require('html-webpack-plugin');
//installed via npm
const webpack = require('webpack');
//to access built-in plugins
module.exports = {
module: {
rules: [
{ test: /.txt$/, use: 'raw-loader' }
]
},
plugins: [
new HtmlWebpackPlugin({template:
'./src/index.html'})
]
};
webpack.config.js
8
15. ● Install webpack server
○ npm i -D webpack-dev-server
● Add scripts to package.json
○ “start:dev” : “webpack-dev-server”
● npm run start:dev
Install Webpack server
15
16. ● Create folder => images.
● Add image in to the folder.
● Insert image in img tag of
index.html
Bundling Images
npm run build Nothing happens!
● npm i -D file-loader
● webpack.config.js
{
test: /.(png|svg|jpg|gif)$/,
use: [ 'file-loader' ]
}
npm run build Creates images in dist
16
17. ● npm i -D node-sass style-loader css-loader
sass-loader mini-css-extract-plugin
● Create folder => styles
● Include main.scss file.
● Import the file.
● In webpack.config.js
{
test: /.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader'
]
}
Bundling SCSS
npm run build
Scss variables found in js
under dist folder.
17
18. Why is webpack necessary?
● Cares about Performance & Load time
● Provides best possible experience
● Improved readability & maintainability of the project.
● Provides features like,
○ Hot Module Replacement
○ Lazy Loading
○ Bundle splitting
○ Hashing
○ Source maps
● Integral part of JS Ecosystem.
18