"Webpack Study notes (i)" A preliminary study on the Popular Front-end modular tools Webpack

Source: Internet
Author: User
Tags script tag

From development files to production files

 one day I suddenly realized a problem, when I used the react framework to build an application, I used the sass/less,jsx template and the ES6 syntax to develop under the editor, using these formulations to improve the efficiency of development. But the browser itself is not able to "understand" these grammars. Just like this picture below:What exactly do we need to do in developing code files----and in the process of converting production code files? Yes, it's all about Webpack (or gulp): turn a picture of Webpack official website, Webpack can less/sass files, JSON files, and even CSS files, all packaged into JS files and static resource files (image)

the common role of webpack and gulp and the difference between them:Webpack and Gulp are not essentially the same type of tools, but they can all accomplish the following tasks:

Webpack: A modular tool (a module bundle)Gulp: A task runner (a tasks Runner) in the use of react/vue/angular to build a single page application, we can use Webpack instead of gulp work, convenient and fast. The specific difference between the two, we do not repeat here, we have access to information on their own. Here I mainly introduce the use of Webpack  in addition to using Webpack to develop code-to-Production code conversion, why do we use it to do some other work, such as file packaging (file merge), Js/css compression?   Why use Webpack to implement file packaging?  Why do we have to do the work of file packing, what is the point of doing this? It starts with the <script> tag that we once loved. For many beginners, it is normal to write a large number of <script> tags on each HTML page. This HTML file is then generated when the deployment is launched
There's nothing wrong with looking at it, but think about it, each page has so many HTTP requests, and a lot of pages are stacked together, which greatly reduces the performance of the page and makes the page slow to load. So we thought, could you combine countless script files into one (or several) files so that the number of requests is not greatly reduced? Yes, that's what Webpack is doing . Why use Webpack to achieve JS compression?  As with packaging, compressing files is also designed to improve page performance (you can feel the importance of page performance in combination with the experience of those very slow web sites). When you use Webpack to compress a file, it does the following:
 
 
    • Delete a comment
    • Remove spaces (so we occasionally see no interval or only one line of JS code)
    • Shorten variable name, function name and parameter name (var myName = ' Peng Bay ')-->var a = ' Peng Bay '
the benefits of doing this:
    • Reduce file volume, speed transfer, and improve page performance
    • Code obfuscation, damage to readability, protection of creators ' intellectual property
(Note: This process is irreversible!) Need to do backup work beforehand)Why use Webpack to implement sass,less compilation and jsx template file conversion?  As mentioned above, through the conversion of Webpack, from the browser can not "understand" the development of code to generate a browser to "understand" the Production Code Commonjs and AMD specifications from a lot of <script> to Webpack's extensive use, is actually the front-end modular development process, while there are two main modular standard COMMONJS and Amd,webpack is based on Commonjs, ( Of course also compatible with the write AMD, but not recommended ) here is the Commonjs module: Const MODULEINPUT = require (' Moduleinpu ')//Input modulemodule.exports = {//Output module  ...} below I hit how to implement the above three functions with Webpack: first you have to create a file webpacktest, enter the directory in the terminal, write the NPM install WEBPACK-G, install successfully1 File packaging (spa-single page application) 1-1 After installing Webpack, create such a directory: 1-2: Writing content to component files and dist/index.html files Dist represents the production directory, component is the development directory, we usually develop only in the component directory is completed. Dist/index.html was created by us manually, with the following content: 
<!doctype html>

we want to pack all the files in the component into dist/ab.js with the Webpack file, and then dist/index.html can refer to the Dist/ab.js file. component/a.js Content:
Console.log (' I am a a.js file ');
component/b.js content:
Console.log ("I am a b.js file");
component/ab.js content:
Require ('./a ') require ('./b ') Console.log (' I am ab.js, I require a.js files and b.js files ');
 1-3Write content to Webpack.config.js:
var path = require (' path ') Module.exports = {    entry:{       ab: './component/ab.js ',    },    output:{        FileName: ' bundle.js ',        path:path.resolve (__dirname, ' dist '),    },}

Webpack requires that the output module of the Webpack.config.js be an object and contains two basic properties: entry and output. Entry, as the name implies, the entry file, the above code indicates that Component/ab.js is a portal file, Output/bundle.js is the output file. Since Component/ab.js introduced (require) a.js files and b.js files, these three files are packaged in Dist/bundle.js together (note: The relative path can be written in entry)
var path = require (' path ') path.resolve (__dirname, ' dist ')
What does this piece of code mean? Path is the built-in module of node, resolve is a method of it, __dirname represents the absolute path of the current directory on disk, Path.resolve (__dirname, ' dist ') = __dirname + '/dist ', In my Mac it's equivalent to users/penghuwan/myprogram/webpacktest/dist(note: must be an absolute path and cannot be a relative path!) ) 1-4 ok! The writing is all written, next, in the terminal into the directory, write Webpack carriage returnall three files under component are packed and come back to see our catalogue .

one more Dist/bundle.js file! Let's see what's Inside:

A.js,b.js and Ab.js, which we wrote separately, were packaged dist/ab.js.  At the same time, we previously in the dist/index.html <script type= "Text/javascript" src= "ab.js" ></script></ Body> not be able to play a role? Let's find the file on the disk open and find the console output:

graphically describe the above process,Webpack constructs a dependency tree recursively, which includes each module you need for your application, and then packages all modules into a small number of packages (bundles) -usually only one package- Can be loaded by the browser . 2 Multi-entry files  2-1 in the above example, we only write a portal file in entry, can we write more than one entry file at a time? This is of course possible, first modify our file structure in component:

C.js/d.js/cd.js and a.js/b.js/ab.js are structurally identical, just the output text is different, here not much to repeat, and then modify our Webpack.config.js
var path = require (' path ') Module.exports = {    entry:{       ab: './component/ab.js ',       CD: './component/cd.js '     },    output:{        filename: ' [name].js ',        path:path.resolve (__dirname, ' dist '),}    ,}
 The name here is the placeholder [name] corresponding to the [AB] and [CD] written in entry, which means that the generated under Dist will no longer be the bundle.js mentioned above, but Ab.js and cd.js two JS files  2-2 to revise our dist/index.html:
<!doctype html><script type= "Text/javascript" src= "./ab.js" ></script></body>  <script type= "text/ JavaScript "src="./cd.js "></script></body>

2-3 Then also enter the terminal, write Webpack and return to the directory, at this time has generated dist/ab.js and dist/cd.js two files

2-4 open dist/index.html in the browser, output:The above process is described graphically as follows, and A/b/ab and C/D/CD are packaged as two bundles and introduced into each other due to the dependency book established by the reference relationship dist/index.html

3 Add a hash value tag for the output file to avoid reloading the same fileTwo times before and after the terminal input Webpack packaging, even if all the files in the component have not changed, the resources are to be reloaded again. Similarly, in production, every time you need to update content in your code, the server must be redeployed and then re-downloaded by all clients. This is obviously inefficient because it can be slow to get resources over the network. So how can we avoid this problem? ——— provide a hash value token for the bundle file in output:each time the output file is built, if the code changes, the output file will generate a different hash value, then reload the resources, but if the code is not changed, the output file hash value does not change, the system will default to use the original cached output file  3-1 Modify our webpack.config.js: 
var path = require (' path '= {    entry:{       ab:'./component/ab.js ',       CD:'. /component/cd.js '    },    output:{        filename:' [name]-[hash]. js ',        path: Path.resolve (__dirname,' Dist '),    },}

Dist Directory after Packaging: (Dist/ab.js and Dist/cd.js in the previous example have been deleted)

a new problem with writing a hash value--Change the src of JS in dist/index.html every time Because the hash we generate is constantly changing, at the same time index.html must constantly change the value of SRC in the <script> tag 4 Solving new problems caused by hash value  4-1Using the Html-webpack-plugin plug-in, the Webpack.config.js output module object has a plugins property, which is an array where the array item is created by the plugin object in the terminal written to NPM install Html-webpack-plugin--save-dev, modify the configuration of the webpack.config.js after installation:
var path = require (' path ')var htmlwebpackplugin = require (' Html-webpack-plugin '); Module.exports = {    entry:{       ab: './component/ab.js ',       CD: './component/cd.js '    },    output:{        FileName: ' [name]-[hash].js ',        path:path.resolve (__dirname, ' dist '),    },    plugins:[      New Htmlwebpackplugin ()    ]}

  4-2 in the terminal input Webpack Enter, open our Dist/index, incredibly has been automatically written src with hash value of the script tag!

"Note" This time the dist/index.html is automatically generated by Webpack, and the previous examples were written by us manually5 Specifying a template for the generated index.html  5-1 But let's think about another problem, this dist/html is automatically generated, we can do some modification, such as specifying a template. Use the component/index.html in the development development file to generate dist.html for the template? First create a component/index.html file, write:
<! DOCTYPE html>

5-2 Modify our webpack.config.js:
var path = require (' path ') var Htmlwebpackplugin = require (' Html-webpack-plugin '); module.exports = {    entry:{       AB : './component/ab.js ',       CD: './component/cd.js ',    output:{        filename: ' [name]-[hash].js ',        path :p ath.resolve (__dirname, ' dist '),    },    plugins:[      new Htmlwebpackplugin ({        Template: '). Component/index.html '}      )    }

5-3 writes the template property to the Htmlwebpackplugin parameter object, specifies Component/index.js, returns to the terminal, writes Webpack, and then lets take a look at the dist/ Index.html

describe the above process graphically:6 Packaging Multi-page applications with Webpack (MPA) talk about Spa (Sing page application) and MPa (Mutiple page aplication), spa and MPA refer to single-page applications and multi-page applications , before we pack the spa, So how to pack MPa? It is very simple to write multiple Htmlwebpackplugin objects in plugins, and then you need to indicate the FileName property values of the different files and the chunks property values-their corresponding bundle files 6-1 Rewrite our webpack.config.js file:
 var  path = require (' path '  = {entry:{ab:  './component/ab.js ' }, output:{filename:  ' [name ]-[hash].js '  ' Dist '         new htmlwebpackplugin ({        FileName: ' ab.html ', Template: './component/index.html ', chunks:[' AB '}), new Htmlwebpackplugin ({ FileName: ' cd.html ', Template: './component/index.html ', chunks:[' CD '  

6-2 after packaging generated dist/ab.html and dist/cd.html in Dist, the browser opens ab.html and console output:Browser opens cd.html, console output:illustrate the above process:

"Webpack Study notes (i)" A preliminary study on the Popular Front-end modular tools Webpack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.