Webpack Introduction

18
- Anjali Chawla SDE-I,

Transcript of Webpack Introduction

Page 1: Webpack Introduction

- Anjali ChawlaSDE-I, Expedia

Page 2: Webpack Introduction

2 of 18

“Every static asset should be able to be a module”Not just js; css, images, fonts, … all are modules

Page 3: Webpack Introduction

3 of 18

By the end of the presentation

• What is webpack• Why should I use web pack• How do I use webpack• Features

Page 4: Webpack Introduction

4 of 18

What is webpack?• Webpack is a module bundler. It takes modules with dependencies

and generates static assets representing those modules.• You can use webpack for both your client side JS files as well as your

server side node JS files.

Image source: https://webpack.github.io/docs

Page 5: Webpack Introduction

5 of 18

What does webpack do• Manage dependencies

• require • import (e.g. CommonJS, AMD, ES6, etc.)

• Build tasks - convert and preprocess • Minify• Combine• Sass / less conversion• Babel transpile

• It combines the build system and module bundling, i.e. instead of building sass and optimizing images in one part of project, and then combining the script files in another, it combines everything in the module itself

Page 6: Webpack Introduction

6 of 18

What does webpack do

Wraps everything that is a part of the module in the module itself, and creates a bundle of it.

Page 7: Webpack Introduction

7 of 18

• Code Splitting : Split the dependency tree into chunks and load on demand• Maintain the dependency tree• Create chunks of the modules and load them from webpack runtime

environment• Reduce initial loading time• Reduce the number of HTTP requests / for HTTP 2.0 use plugins to reduce the

chunk size to optimize it for caching• Optimize the combined file so as to reduce the load time, while ensuring

avoiding of code redundancy

Why should I use webpack – The Plus Factor

Page 8: Webpack Introduction

8 of 18

Code Splitting• It’s the idea that you define, in your code, “split points”: areas of your

code that could be easily split off into a separate file and then load on-demand. • Syntax:

// This is a split point require.ensure([], () => { //use require for AMD

// All the code in here, and everything that is imported will be in a separate file const library = require('some-big-library'); $('foo').click(() => library.doSomething());

}, <‘name of the chunk’>);

Page 9: Webpack Introduction

9 of 18

Code Splitting• A split point creates a chunk for the dependencies.• Chunk is automatically checked for repeatition of modules and split

accordingly.• A chunk is loaded at runtime as jsonp and is loaded only once.• This will remove all modules in the vendor chunk from the app chunk.

The bundle.js will now contain just your app code, without any of its dependencies. These are in vendor.bundle.js.

var webpack = require("webpack"); module.exports = { entry: {

app: "./app.js", vendor: ["jquery", "underscore", ...], },

output: { filename: "bundle.js" }, plugins: [

new webpack.optimize.CommonsChunkPlugin(/*chunkName=*/”vendor", /* filename=*/ "vendor.bundle.js” ) ] };

Page 10: Webpack Introduction

10 of 18

ProfilingCreating json file• webpack --profile --json > stats.json

Tools to analyze profile• http://webpack.github.io/analyse/• http://chrisbateman.github.io/webpack-visualizer/

Page 11: Webpack Introduction

11 of 18

Multiple entry pointsUnderstanding entry point - Webpack.config.js

module.exports = { entry: './src/index.js', output: {

path: './builds', filename: 'bundle.js'

} };

$ = require(jquery);

Reads entry point and load the dependencies

./src/index.js

node_modules Project modules

1

./builds/bundle.js

Bundles module into a single file

2

Page 12: Webpack Introduction

12 of 18

Multiple entry points• It will build multiple bundles at once. Additional chunks can be shared

between these entry chunks and modules are only built once.• Every entry chunk contains the webpack runtime.

{ entry: {

a: "./a", b: "./b", c: ["./c", "./d"]

}, output: {

path: path.join(__dirname, "dist"), filename: "[name].entry.js"

} }

Page 13: Webpack Introduction

13 of 18

Loaders• Functions (running in node.js) that take the source of a resource file

as the parameter and return the new source.• Loaders can be chained and the final loader is expected to return

JavaScript. They are applied right to left.• You can write your custom loaders in node.js compatible JavaScript

{ module: {

loaders: [ { test: /\.jade$/, loader: "jade" }, // => "jade" loader is used for ".jade" files { test: /\.css$/, loader: "style!css" }, // => "style" and "css" loader is used for ".css" files // Alternative syntax: { test: /\.css$/, loaders: ["style", "css"] }, ]

} }

Page 14: Webpack Introduction

14 of 18

Plugin System• Plugins differ from loaders in the sense that instead of only executing

on a certain set of files, and being more of a “pipe”, they execute on all files and perform more advanced actions, that aren’t necessarily related to transformations.• Example, CommonChunksPlugin: Analyzes your chunks for recurring

dependencies, and extracts them somewhere else. It can be a completely separate file (like vendor.js) or it can be your main file.

Page 15: Webpack Introduction

15 of 18

Hot Module Replacement• HMR is a way of exchanging modules in a running application (and

adding/removing modules). Updating changed modules without a full page reload.• app code asks HMR runtime to check for updates in the manifest files created by

webpack compiler.• If an update exists, it is applied and only that part of the application is reloaded /

updated.• Every module has to enable HMR, explicitly

var requestHandler = require("./handler.js"); var server = require("http").createServer(); server.on("request", requestHandler); server.listen(8080); if(module.hot) {// check if HMR is enabled

module.hot.accept("./handler.js", function() {{ // accept update of dependency server.removeListener("request", requestHandler); // replace request handler of serverrequestHandler = require("./handler.js"); server.on("request", requestHandler); });

}

Page 16: Webpack Introduction

16 of 18

Extras• We have pre and post loaders (e.g. for jsLint)• Integrating webpack with gulp / grunt

var gulp = require('gulp'); var webpack = require('webpack-stream');gulp.task('default', function(callback) {

return gulp.src('src/entry.js') .pipe(webpack()) .pipe(gulp.dest('dist/'));});

module.exports = function(grunt) { grunt.loadNpmTasks("grunt-webpack");

grunt.initConfig({ webpack: {

options: { // configuration for all builds }, build: { // configuration for this build }

}, };

Page 17: Webpack Introduction

17 of 18

Getting started• Required: node, npm

$ npm install webpack –g

webpack // for building once for developmentwebpack -p // for building once for production (minification)webpack --watch // for continuous incremental build in development (fast!)webpack -d // to include source maps

Page 18: Webpack Introduction

18 of 18

References

• Documentation: http://webpack.github.io/docs/• Loaders: http://webpack.github.io/docs/list-of-loaders.html• Plugins: http://webpack.github.io/docs/list-of-plugins.html• https://blog.madewithlove.be/post/webpack-your-bags/