Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Webpack and Web Performance Optimization

1,062 views

Published on

Introduce Webpack and how to use it improve web performance.

Published in: Technology
  • Be the first to comment

Webpack and Web Performance Optimization

  1. 1. Webpack and Web Performance Optimization Blackie.Tsai Blackie.tsai@xuenn.com 2016/11/18
  2. 2. Agenda • Webpack Introduction • Web Optimization • Modularized Javascript and React • Collaborate with .net MVC
  3. 3. Webpack Introduction
  4. 4. • 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
  5. 5. 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/
  6. 6. 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
  7. 7. 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
  8. 8. Webpack flow
  9. 9. 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
  10. 10. 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" } ] } };
  11. 11. Webpack Config File • entry • Setup entry file • output • Determine output path and file name • module(optional) • Setup loaders
  12. 12. Environment Setup
  13. 13. 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
  14. 14. [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
  15. 15. [NPM]webpack-notifier • https://www.npmjs.com/package/webpack-notifier • npm install --save-dev webpack-notifier
  16. 16. WebPack Task Runner • https://visualstudiogallery.msdn.microsoft.com/5497fd10-b1ba- 474c-8991-1438ae47012a
  17. 17. Webpack Tutorial
  18. 18. Welcome Webpack • http://webpack.github.io/docs/tutorials/getting-started/
  19. 19. Web Optimization
  20. 20. • 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
  21. 21. • Image Optimization • Reduce HTTP Requests • Minify CSS and Javascript • Critical Path and Render Blocking Resources (CSS + JS) • Reduce Latency with a CDN • Avoid 301 Redirects • Caching • Web Font Performance • Enable Gzip Compression • Fix 404 Errors • Serve Scaled Images Top tips for Web Performance Optimization
  22. 22. 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
  23. 23. Loading JavaScript Dynamically
  24. 24. Delaying Image Loading • a.k.a Image Lazy Loading Solution To Lazy Loading SEO Impact
  25. 25. 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
  26. 26. 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
  27. 27. 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)
  28. 28. 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
  29. 29. 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
  30. 30. Play with Gulp
  31. 31. Gulp 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
  32. 32. 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
  33. 33. 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
  34. 34. 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(); }); });
  35. 35. 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
  36. 36. • 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
  37. 37. Modularized JavaScript and React
  38. 38. Modularized JavaScript • Pros • Encapsulation • Decoupling • Organization • No global scope pollution • Security • Re-use • Cons • More difficult to release • Complex dependency
  39. 39. Thinking in React
  40. 40. ReactJS+Webpack Structure
  41. 41. Babel Introdcution
  42. 42. 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.
  43. 43. Webpack+Babel+React
  44. 44. 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.
  45. 45. Webpack for React • Webpack is a bundler. It'll take a bunch of loose Javascript files and build a single file from the lot
  46. 46. 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:
  47. 47. Babel-loader • This package allows transpiling JavaScript files using Babel and webpack. https://github.com/babel/babel-loader
  48. 48. 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.
  49. 49. Environment Setup
  50. 50. Visual Studio 2015 with latest update • https://blogs.msdn.microsoft.com/visualstudio/2015/06/10/javas cript-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
  51. 51. React Snippet Pack • https://visualstudiogallery.msdn.microsoft.com/234d79e9-f0fd- 41e1-a926-850da8e8c7d7
  52. 52. Collaborate with .net MVC
  53. 53. • 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
  54. 54. Project Structure
  55. 55. package.json
  56. 56. Layout and View
  57. 57. ES6 to ES5(using Babel)
  58. 58. Advance Webpack
  59. 59. Reference • 設定開發React的環境 • 設定開發React的環境 - React Hot Loader • Production optimization with React and Webpack
  60. 60. Q & A
  61. 61. 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!
  62. 62. 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
  63. 63. • 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

×