Param Singh
Why Webpack?
Webpack is a bundling tool that puts all of your assets, including Javascript, images, fonts, and CSS, in a dependency graph.
In the early days, we "managed" Javascript dependencies by including files in a specific order:
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="dist/lib/timepicker/jquery.timepicker.js"></script>
<script src="dist/lib/jquery.datepicker.js"></script>
<script src="main.js"></script>
// build-script.js
var scripts = [
'jquery.min.js',
'jquery.some.plugin.js',
'main.js'
].concat().uglify().writeTo('bundle.js');
// Everything our app needs!
<script src="bundle.js"></script>
//math.js
module.exports = {
sum: function(a, b) {
return a + b;
},
cube: function(a) {
return a * a * a;
},
multiple: function(a, b) {
return a * b;
}
};
//index.js
const { cube, sum } = require('./math.js');
console.log(cube(3), sum(3, 2));
using static System.Console;
using static System.Math;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
import java.util.Calendar;
import java.util.Date;
import { ZipCodeValidator } from "./ZipCodeValidator";
let myValidator = new ZipCodeValidator();
Need this modular goodness for UI development
import gulp from "gulp";
import browserify from "browserify";
import uglify from "gulp-uglify";
import source from "vinyl-source-stream";
import buffer from "vinyl-buffer";
import sourcemaps from 'gulp-sourcemaps';
gulp.task('default', () => {
browserify({
entries: 'src/utils.js',
debug: true
})
.bundle()
.pipe(source('utils.min.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist'));
});
In the land of JavaScript, no one is king for long.
#SurvivalOfTheFittest ~ Charles Darwin
import logo from 'assets/logo.png';
img.src = logo;
npm install --save-dev webpack
npm install --save-dev webpack@<version>
npm install --save-dev webpack-cli
1. Starts from the entry point './src/index.js'.
2. Parses the file/modules recursively and wraps them in a function body as
index.js
chunkA.js
3. Hacks the exports object and have it populated with the exported members from that file.
4. Assign every module and id as it's path and uses it to import other modules.
1. It's called for every module while traversing the dependency tree.
2. Keeps a cached registry as installedModules and returns from there if the module of the moduleId passed is already loaded.
3. If not, it creates a module object with keys as id, loaded flag and its exported members.
4. Calls the wrapper function of that module with the params passed.
5. Flag the given module as loaded.
6. Return all the exported members of that module.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
mode: 'development',
target: 'web',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['babel/preset-env']
}
}
]
},
]
},
plugins: [
new HtmlWebpackPlugin()
]
};
entry: string | [string] | object { <key>: string | [string] }
entry: './src/index.js'
// or
entry: {
home: "./home.js",
about: "./about.js",
contact: "./contact.js"
}
//or
entry: {
vendor: [
'moment',
'lodash',
'react',
'react-dom'
],
main: './client.js'
}
// or
entry: [
'polyfills',
'./src/index.js'
]
context: path.resolve(__dirname, 'src')
// Use this
entry: './index.js',
// Instead of
entry: './src/index.js',
The base directory, an absolute path, for resolving entry points and loaders from configuration.
path: path.resolve(__dirname, 'dist')
Contains set of options instructing webpack on how and where it should output your bundles, assets and anything else.
output.path
filename: '[name].bundle.js' | '[name]-[id].bundle.[hash].js'
output.filename
libraryTarget: 'umd' | 'amd' | 'commonjs' | 'var' | 'global', 'window',
output.libraryTarget
library: 'Dandelion'
output.library
publicPath: "https://cdn.example.com/assets/" | "/assets/"
output.publicPath
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'react']
}
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader" // compiles Sass to CSS
}]
}
]
}
These options determine how the different types of modules within a project will be treated.
Out of the box, webpack only understands JavaScript files. Loaders allow webpack to process other types of files and converting them into valid modules that can be consumed by your application and added to the dependency graph.
module.exports = function (content) {
const result = content.replace(/\/\/.*\n/g, '');
this.callback(null, content);
}
module.exports = function(content, map, meta) {
var callback = this.async();
someAsyncOperation(content, function(err, result) {
if (err) return callback(err);
callback(null, result, map, meta);
});
};
Async Loader
Loader for removing comments
plugins: [
new HtmlWebpackPlugin({ title: 'My Page Title' }),
new ManifestPlugin(),
new CleanWebpackPlugin(['dist']),
]
externals : {
react: 'react'
}
// or
externals : {
lodash : {
commonjs: "lodash",
amd: "lodash",
root: "_" // indicates global variable
}
}
// or
externals : {
subtract : {
root: ["math", "subtract"]
}
}
The externals configuration option provides a way of excluding dependencies from the output bundles.
Instead, the created bundle relies on that dependency to be present in the consumer's environment
module.exports = {
mode: 'production' | 'development' | 'none'
};
There are three general approaches to code splitting available:
{
"plugins": ["syntax-dynamic-import"]
}
.babelrc
application.js?build=1
application.css?build=1
// webpack.config.js
module.exports = {
...
output: {
...
filename: '[name].[chunkhash].js'
}
}
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest'
})
optimization: {
runtimeChunk: {
name: "manifest",
},
},
Caveats
Provides you with a simple web server and the ability to use live reloading
Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running, without a full reload. This can significantly speed up development in a few ways:
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
if (process.env.WEBPACK_ANALYZE) {
config.plugins.push(new BundleAnalyzerPlugin());
}
Thank You!
@paramsingh_66174