Webpack and Web Performance Optimization

63
Webpack and Web Performance Optimization Blackie.Tsai [email protected] 2016/11/18

Transcript of Webpack and Web Performance Optimization

Page 1: Webpack and Web Performance Optimization

Webpack and Web Performance Optimization

Blackie.Tsai

[email protected]

2016/11/18

Page 2: Webpack and Web Performance Optimization

Agenda• Webpack Introduction• Web Optimization• Modularized Javascript and React• Collaborate with .net MVC

Page 3: Webpack and Web Performance Optimization

Webpack Introduction

Page 4: Webpack and Web Performance Optimization

• Today’s Web Apps Trendy• More and more JavaScript is being used.• Modern browsers are offering a wider range of interfaces.• Fewer full page reloads → even more code in a page

• As a result there is a lot of code on the client side! A big code base needs to be organized. Module systems offer the option to split your code base into modules

Current problems

Page 5: Webpack and Web Performance Optimization

Webpack - A Module Bundler• A bundler for javascript and friends. Packs many modules into a

few bundled assets. Code Splitting allows to load parts for the application on demand. Through "loaders," modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff. https://webpack.github.io• Usage: https://webpack.github.io/docs/tutorials/getting-started/

Page 6: Webpack and Web Performance Optimization

Goals• Split the dependency tree into chunks loaded on demand• Keep initial loading time low• Every static asset should be able to be a module• Ability to integrate 3rd-party libraries as modules• Ability to customize nearly every part of the module bundler• Suited for big projects

Page 7: Webpack and Web Performance Optimization

Features• Code Splitting

• allows you to split your codebase into multiple chunks. Chunks are loaded asynchronously at runtime. This reduces the initial loading time.

• Optimizations• can do many optimizations to reduce the output size of your JavaScript by de-

duplicating frequently used modules, minifying, and giving you full control of what is loaded initially and what is loaded at runtime through code splitting.

• Loaders• enables use of loaders to preprocess files. This allows you to bundle any static

resource way beyond JavaScript. You can easily write your own loaders using node.js.  

• Module Format (AMD/CommonJS)• supports both AMD and CommonJS module styles.

• Plug-in System• webpack features a rich plugin system and allows you to customize

Page 8: Webpack and Web Performance Optimization

Webpack flow

Page 9: Webpack and Web Performance Optimization

Loader• Loaders allow you to preprocess files as you require() or “load” them. • Loaders are kind of like “tasks” in other build tools, and provide a powerful way to handle frontend build steps. • Loaders can transform files from a different language like, CoffeeScript to JavaScript, or inline images as data URLs. • Loaders even allow you to do things like require() css files right in your JavaScript! You can import other Loaders to help you. • E.g. CSS-LOADER, IMAGE LOADER, BUNDLE-LOADER

Page 10: Webpack and Web Performance Optimization

Loader - Sample• Webpack transform a module with a loader

• ! syntax separating the loader from the module path? Loaders, like modules can also be specified with a relative path (as if you were requiring it) instead of the loader name

• Chained together by separating loaders with the !

• Loaders  with Parameters

• loaders by config

var moduleWithOneLoader = require("my-loader!./my-awesome-module");

var moduleWithLoaders = require("style-loader!css-loader!less-loader!./my-styles.less");

var moduleWithLoaderHasParameters = require("loader?with=parameter!./file");

{ module: { loaders: [ { test: /\.coffee$/, loader: "coffee-loader" } ], preLoaders: [ { test: /\.coffee$/, loader: "coffee-hint-loader" } ] } };

Page 11: Webpack and Web Performance Optimization

Webpack Config File• entry• Setup entry file

• output• Determine output path and file name

• module(optional)• Setup loaders

Page 12: Webpack and Web Performance Optimization

Environment Setup

Page 13: Webpack and Web Performance Optimization

NodeJS• Node.js® is a JavaScript runtime built on 

Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. • Node.js' package ecosystem, npm, is the largest ecosystem of

open source libraries in the world.• https://nodejs.org/dist/v4.5.0/node-v4.5.0-x64.msi• https://nodejs.org/dist/v6.6.0/node-v6.6.0-x64.msi

Page 14: Webpack and Web Performance Optimization

[NPM]Webpack• https://www.npmjs.com/package/webpack• Setup• Project: npm install webpack --save-dev• Global: npm install webpack –g

• Common Commands(usually execute with webpack.config.js file)• webpack : execute one time in dev mode. E.g. webpack main.js

bundle.js• webpack -p : execute for production-ready • webpack --watch : execute and watch change to execute on

background• webpack --progress --colors : execute with progress bar and colors

Page 15: Webpack and Web Performance Optimization

[NPM]webpack-notifier• https://www.npmjs.com/package/webpack-notifier• npm install --save-dev webpack-notifier

Page 16: Webpack and Web Performance Optimization

WebPack Task Runner• https://visualstudiogallery.msdn.microsoft.com/5497fd10-b1ba-474c-8991-1438ae47012a

Page 17: Webpack and Web Performance Optimization

Webpack Tutorial

Page 18: Webpack and Web Performance Optimization

Welcome Webpack • http://webpack.github.io/docs/tutorials/getting-started/

Page 19: Webpack and Web Performance Optimization

Web Optimization

Page 20: Webpack and Web Performance Optimization

• Unoptimized Resource(js, css, images)• Sites impacted: 90%

• Content Served Without HTTP Compression• Sites impacted: 72%

• Without Concatenate Resource(js, css or images) to one Request• Sites impacted: 69%

• Too much HTTP Requests• Sites impacted: 69%

• Without Caching Information• Sites impacted: 65%

• Domain Sharding Not Implemented• Sites impacted: 64%

Top issue for Web Performance

Page 22: Webpack and Web Performance Optimization

Adaptive Web Concept

Header

HTML

iframe

img

media

• CSS, icon and fonts• Most file can Concatenate

(CSS merge and image sprite )• Loading first and sequence with blocking

• Body content, JS and other resource• Bigger file size than Header• Most file can’t Concatenate

(exclude JS bundle and image sprite )• Loading/Executing later when read the content with non-blocking

body

Page 23: Webpack and Web Performance Optimization

Loading JavaScript Dynamically

Page 24: Webpack and Web Performance Optimization

Delaying Image Loading• a.k.a Image Lazy Loading

Solution To Lazy Loading SEO Impact

Page 25: Webpack and Web Performance Optimization

Web Optimize Before Mobile Lite• Now• SBK have 15 requests for total 500KB transferred• 188 have 8 requests for total 600KB transferred

• Action• Eliminate render-blocking JavaScript and CSS in above-the-fold content• Less request• Can improve 40% for latency issue on too many requests, from 23

to 14• SBK • Combine JS request

• 188(Brand) • Combine JS request• Refine 188(Brand) header/footer for provide less request version

for SBK

Page 26: Webpack and Web Performance Optimization

Reduce less with low User impact• Changes• General• No image(jpg, png and gif) file• Use CSS, Font(include icon) and HTML• Only one kind of font for Mobile Lite(Only Lato-Regular, no Lato-

Bold)• Pagination for Today

• Homepage• No image on each feature event

• All Market• Score Board with simple background color

• Estimated improvement• Reduce 4 request• Reduce 180 KB

Page 27: Webpack and Web Performance Optimization

Reduce more but high User impact• Changes• General• No Auto refresh, using manually refresh(e.g. can click every 30s)

• All Market• No Live Center(5 sec auto-refresh with 2.5 KB=>1 min with 30KB)

• Estimated improvement• Reduce 1 request • Reduce 20 KB(exclude Live Center)

Page 28: Webpack and Web Performance Optimization

Cut function but Company impact• Changes• Homepage• Only display 1st feature event• Only display top N priority sports events

• Main Odds• Only display top N priority competition event

• All Market• Display predefine priority markets only

• Estimated improvement• Reduce 50 KB

Page 29: Webpack and Web Performance Optimization

Comparison

Original Web Optimized Low User Impact High User Impact Company Impact

Request 23 14 10 9 9

Transferred size(KB) 1, 100 1,100 920 930 880

Page 30: Webpack and Web Performance Optimization

Play with Gulp

Page 31: Webpack and Web Performance Optimization

Gulp

31

Gulp is a Task Runner build by JavaScript to help automation. The less work you have to do when performing repetitive tasks like minification, compilation, unit testing, linting, etc. After you've configured it through a Gulpfile, a task runner can do most of that mundane work for team

• Minify JavaScript, CSS files• Combine JavaScript, CSS files(including

compile Sass and Less) and Image Sprites

• Testing• Format or Code Rule check

Page 32: Webpack and Web Performance Optimization

Development Flow - Developing• Integrate with Visual Studio with Task Runner Explorer, Gulp for VS• Help doing below task when ITC doing developing• Concatenation and minifying• Compile SASS file to CSS file on runtime• Testing minify JavaScript, CSS files• Testing combine JavaScript, CSS files(Sass and Less) and Image Sprites • Validate front-end coding rule

Page 33: Webpack and Web Performance Optimization

Gulp Plugin• gulp-concat : file concatenate• gulp-minify-css : CSS minifying• gulp-uglify : Compressed Javascript(Can replace by Webpack)• gulp-rename : File rename• gulp-html-replace : Replace target source path • gulp-minify-html : Compressed HTML• Ref• http://www.oxxostudio.tw/articles/201503/gulp-2-compress-js-css.html• http://www.oxxostudio.tw/articles/201503/gulp-3-compress-html.html

Page 34: Webpack and Web Performance Optimization

Integrate with Webpack• With webpack-stream (not recommened)• https://github.com/shama/webpack-stream• Run webpack as a stream to conveniently integrate with gulp.• Big issue=>gulp & webpack整合,鱼与熊掌我都要!

• Without webpack-stream • https://webpack.github.io/docs/usage-with-gulp.html

var gulp = require("gulp"); var gutil = require("gulp-util"); var webpack = require("webpack"); var WebpackDevServer = require("webpack-dev-server");

gulp.task("webpack", function(callback) { // run webpack webpack({

// configuration }, function(err, stats) {

if(err) throw new gutil.PluginError("webpack", err); gutil.log("[webpack]", stats.toString({

// output options })); callback();

}); });

Page 35: Webpack and Web Performance Optimization

Development Flow – Build and Release• Gulp help doing below task

• Compile SASS file to CSS file• Minify JavaScript, CSS, HTML files(Release version)• Concatenate JavaScript, CSS files(including compile Sass and Less) and Image

Sprites(Release version)• [Optional]Generate Format or Code Rule report• [Optional]Generate Front-end test report

• Jenkins help doing below task• Trigger Grunt to build Release version• Build and Release DEV(daily)

• Validate Unit test• Validate Integration test• Validate Automation test(Selenium)• Validate Web performance test(YSlow, Phantomjs or etc…)

• Build and Release QAT• Prepare UAT release package• Aggregate and Sent release report

Page 36: Webpack and Web Performance Optimization

• General• Avoid 301 Redirects• Fix All 404 Errors• Loading Resources On-demand• Avoid Render Blocking

• Static content optimize• Concatenate(CSS merge 、 JS bundle 、 image sprite )• Compression(gzip 、 minify, image compression)

• Request optimize• CDN• Front-end Cache• Request Tuning and Combine• Domain Sharding

Web Optimize

Page 37: Webpack and Web Performance Optimization

Modularized JavaScript and React

Page 38: Webpack and Web Performance Optimization

Modularized JavaScript• Pros• Encapsulation• Decoupling• Organization• No global scope pollution• Security• Re-use

• Cons• More difficult to release• Complex dependency

Page 39: Webpack and Web Performance Optimization

Thinking in React

Page 40: Webpack and Web Performance Optimization

ReactJS+Webpack Structure

Page 41: Webpack and Web Performance Optimization

Babel Introdcution

Page 42: Webpack and Web Performance Optimization

Babel - A Tool to convert ES6 to ES5• A Tool to convert ES6 to ES5•  Babel is the most popular tool used to convert ES6 to ES5. It

has various interfaces like a CLI, Node-module and also an online converter. I use the node module for my apps and use theonline version to quickly see the differences.• Why ES6 • 5 JavaScript “Bad” Parts That Are Fixed In ES6• Modularized for React, Babel can convert JSX syntax and strip out type

annotations.

Page 43: Webpack and Web Performance Optimization

Webpack+Babel+React

Page 44: Webpack and Web Performance Optimization

Grunt/Gulp for React• Not all browsers are supporting ES6 yet, so we're going to have

to transpile our ES6 code, turning it into ES5. We're also going to have to handle 'JSX', the special Javascript that we can use for React. We also need to play well with existing code.

Page 45: Webpack and Web Performance Optimization

Webpack for React• Webpack is a bundler. It'll take a bunch of loose Javascript files

and build a single file from the lot

Page 46: Webpack and Web Performance Optimization

Webpack+Babel for React• Even better, we can configure webpack to run files that match

a certain pattern to go through other 'loaders', which can process the files further.• We can use the Babel transpiler to turn an ES6 file to ES5. We

just need the glue to let Webpack use Babel as a loader. That comes in the form of the Babel Loader:

Page 47: Webpack and Web Performance Optimization

Babel-loader• This package allows transpiling JavaScript files using Babel and webpack. https://github.com/babel/babel-loader

Page 48: Webpack and Web Performance Optimization

Dependency• React uses JSX as the XML-like syntax extension over JavaScript

to specify component tree structure, data flow, and event handlers. JSX is processed by Webpack module bundler using specific loaders or convertors.

Page 49: Webpack and Web Performance Optimization

Environment Setup

Page 50: Webpack and Web Performance Optimization

Visual Studio 2015 with latest update• https://blogs.msdn.microsoft.com/visualstudio/2015/06/10/javascript-editor-improvements-in-visual-studio-2015/• https://www.visualstudio.com/en-us/news/vs2015-update1-vs.aspx• React's JSX is now natively supported• ECMAScript 2015 (formerly ECMAScript 6) support

Page 51: Webpack and Web Performance Optimization

React Snippet Pack• https://visualstudiogallery.msdn.microsoft.com/234d79e9-f0fd-41e1-a926-850da8e8c7d7

Page 52: Webpack and Web Performance Optimization

Collaborate with .net MVC

Page 53: Webpack and Web Performance Optimization

• Demo Download• Original post : detail of how to setup up front-end in asp.net core and MVC5, sample is clone from AspNetReactSamples• Setup• Install node and NPM• Go to root directory and use NPM to install js dependency• npm install

• Build with install nuget dependency• Run App

Demo

Page 54: Webpack and Web Performance Optimization

Project Structure

Page 55: Webpack and Web Performance Optimization

package.json

Page 56: Webpack and Web Performance Optimization

Layout and View

Page 57: Webpack and Web Performance Optimization

ES6 to ES5(using Babel)

Page 58: Webpack and Web Performance Optimization

Advance Webpack

Page 60: Webpack and Web Performance Optimization

Q & A

Page 61: Webpack and Web Performance Optimization

11F., No.399, Ruiguang Rd., Neihu Dist., Taipei City 114, Taiwan TEL: +886 2 2798 8529 Fax: +886 2 2798 8531 Website : www.xuenn.com

THANK YOU!

Page 62: Webpack and Web Performance Optimization

Reference• WEBPACK入門教學筆記• 18 Tips for Website Performance Optimization• Performance Guide for Tizen

Web Applications(1): Resource Loading• How-To: Integrate Webpack into Visual Studio 2015• webpack-howto• Pro React : Appendix A: Webpack for React• 如何使用 Webpack 模組整合工具• Webpack: your final module bundler• Getting Started with React & ES6• React Speed Coding• Parallel Downloads Across Domains

Page 63: Webpack and Web Performance Optimization

• dependencies are installed on both:• npm install from a directory that contains package.json• npm install $package on any other directory

• devDependencies are:• also installed on npm install on a directory that contains package.json,

unless you pass the --production flag • not installed on npm install "$package" on any other directory, unless

you give it the --dev option.• are not installed transitively.

• Most important• dependencies are required to run, devDependencies only to develop,

e.g.: unit tests, Coffeescript to Javascript transpilation, minification, ...

[NPM] dependencies and devDependencies