Webpack you deserve-start with four core configurations

Source: Internet
Author: User

Long time no article, but stressed a little, big ~ Bear classmate recently not idle. Learning algorithms, review the computer network, also by the way to learn a bit of webpack, look at the operating system (no way, have not learned, if not learning even the internship written test can not, sad ~ ~). Originally more tangled is to write about the algorithm of the article or about the webpack it. Finally decided to write about Webpack, on the one hand, although just beginning to learn webpack, but his characteristics make people feel very good, but I have a kind of impulse to share; On the other hand, the algorithm to write formulas, this editor seems not very good editing, but also more trouble. Nonsense, this article describes the four core configuration items of Webpack. I do not write well, you can refer to: Chinese documents, English documents. Of course, I can read it.

1. Establish test project and install Webpack

      

  

(1) Establishment of the project directory: mkdir WP

(2) Enter the project directory: CD WP

(3) Create a Package.json file with NPM init (just a name, all the way to the return)

(4) Installing WEBPACK:NPM install--save-dev Webpack

(5) test whether the installation is successful, webpack-v can not find the command, directly in the Package.json scripts plus "Webpack": "Webpack", and then run NPM run webpack-v result is correct

(6) Create source file directory: mkdir SRC

(7) Open the project with the editor: Subl.

Now that the preparation is complete, we get the project directory and the Package.json file as follows:

(Write for a long time, found that after inserting a piece of code can not go to the next line, press a few times Ctrl + Z, incredibly back here, really no language, come again)

2. Use of entry and output

To test first build the following project structure

  

The contents of each file are as follows:

//Index.jsImport A from './js/test.js ';functionHello () {Console.log ("Hello"); Console.log (A);} Hello ();//index.html<! DOCTYPE html> forWebpack study</title>//Webpack.config.jsConst PATH = require ("path"); Module.exports={entry:"./src/index.js", output:{path:path.resolve (__dirname,' Dist '), FileName:"Bundle.js"    },    //module:{},    //plugins:{}}

Run the direct terminal:

Open the project and look at:

Found that generated a dist directory, there is more than one bundle.js file, see Bundle.js found below the contents of our index.js (this is the previous screenshot, a bit inconsistent). What if we declare our dependence on index.js. First in the JS directory to build a test.js file, the contents are as follows:

Const A = "Big ~ bear the most handsome!" "default A;

And then declare a dependency on it in Index.js.

Import A from './js/test.js '; function Hello () {    console.log ("Hello");    Console.log (A);} Hello ();

Pack it up:

The discovery generated a bundle.js, and then there were two files. View Bundle.js will find that the content in the Test.js is added to the inside. Add the following in the index.html:

<type= "Text/javascript"  src= ": /dist/bundle.js "></script>

Preview

  

Discover the introduction of a bundle.js is equivalent to Index.js and Test.js are in, can be used normally. With such a simple example, I believe you already feel the power of Webpack, and the following details the various uses of the entry and output two properties.

  (1) entry:entry Specifies the package entry, either as a string or as an array of strings, or as an object.

A, the case of specifying a string has already been mentioned, it applies to the case of a single entry.

B, specify a string array.

In the SRC directory, create index2.js, and modify the configuration file, see below:

Index2.jsfunction Index2 () {    Console.log ("This is index 2"); Index2 ();//webpack.config.jsconst path = require ("path"); module.exports = {    entry:["./src/index.js", "./src/ Index2.js "],    output:{        path:path.resolve (__dirname, ' dist '),        filename:" Bundle.js "    },    // module:{},    //plugins:{}}

Pack it up.

  

We can see that the content we generate is a bit different, and there is a multi behind 3, where a chunk is generated from multiple ingress trigger check dependencies. When your index2.js and index.js are interdependent and you want to pack them together, that's the way you need them. Of Here's a look at what the generated bundle.js looks like.

C:entry value is an object case

In the first case, there is only one key value, which is the same as a case.

Const PATH = require ("path"= {    entry:{        main:"./src/index.js"    } ,    output:{        path:path.resolve (__dirname,' Dist '),        filename:"bundle.js"    },     // module:{},    // plugins:{}}

In the second case, multiple key-value pairs.

Const PATH = require ("path"= {    entry:{        main:"./src/index.js",        Second:"./src/index2.js"    },    output:{        path:path.resolve (__dirname,' Dist ') ,        filename:"[Name]-bundle.js"    },    //  module:{},      plugins:{}}

Notice I changed the output here, otherwise the following error is reported:

  

Follow my changes to the result:

It can be found that two chunk were generated, the names of which were MAIN-BUNDLE.SJ and Second-bundle.js,chunk respectively, and the names were main, second. If you want to put things packaged from multiple entry files into different files, then this is for you. What's the meaning of that output, start at once.

  (2) Output basic usage

Output has many properties available, and here are some of the most commonly used properties.

    • Path: Specifies an absolute path that indicates where the generated chunk should be placed. Generally this will allow the Path:path.resolve (__dirname, ' Dist '), which represents the absolute path to the Dist directory under the Build project root directory
    • FileName: Specifies the file name of the generated chunk. You can have some special values inside.

[Name]: Indicates the key that you specified when entry the entry, above is main and second

[Hash]: Represents an identity that is packaged once, modified after packaging changes, the same value of the different chunk of a package at a time

[Chunkhash]: Represents the unique identity of each chunk, obviously different chunk is not the same, when something in a chunk changed two times to pack his chunkhash will change, otherwise remain unchanged

[ID]: Represents the number of the chunk, above is 0 and 1

The following points look at the hash and Chunkhash.

Modify Index.js and Repackage

   

Found that we have changed only one index.js, the other has changed the hash.

The following configuration is given to [Chunkhash]

Const PATH = require ("path"= {    entry:{        main:"./src/index.js",        Second:"./src /index2.js "    },    output:{        path:path.resolve (__dirname,' Dist '),        filename: "[Name]-[chunkhash]-bundle.js]     },     // module:{},    // plugins:{}}

Package once and then modify the Index.js again to package the results as follows:

  

found that only the files that we modified correspond to the chunkhash of the chunk have changed, the second has not changed. Using Chunkhash can effectively utilize the cache without having to re-download it all. For example, you are on-line an application, has been accessed by many users, when their browser has a cache, if you modify a file, again on-line, if you use Chunkhash, only the name of the chunk you should have changed, the other file cache can also be used, speed up the loading speed. If you use hash, all the filenames will change, all the files have to be re-downloaded, which is not good.

3. Usage of plugins attribute

You may have noticed that the HTML file in Src did not go to the Dist directory. If we create the HTML file directly in the dist, because our chunk filename is changed, each change should be re-introduced. The following describes the Htmlwebpackplugin plugin to solve this problem, in order to understand the plugins configuration items.

(1) Installation

  

(2) configuration

Const PATH = require ("path");   = require (' Html-webpack-plugin '); = {    entry:{        main:"./src/index.js",        Second:"./src/index2.js"    },    output:{        path:path.resolve (__dirname,' Dist '),        filename:"[name]-[chunkhash]- Bundle.js "    },    //  module:{},    plugins:[      New  htmlwebpackplugin ({        Template:"./src/index.html"    })    ]} 

(3) Packaging

Found a index.html file was generated.

(4) See effect

  

Here is a file cannot be found, because our src folder index.html introduced a bundle.js but now there is no such thing, remove it.

Htmlwebplugin plug-ins also have more configuration items, but also has a very powerful features, details see official website, here is just a point.

4. Module Configuration Items

The module configuration item is used to specify loader, loader is essentially the tool used to preprocess our resources, making it easy for webpack to treat them as modules. The following is an example of babel-loader to explain this configuration item.

(1) installation (not finished)

  

(2) configuration

  

Const PATH = require ("path"); Const Htmlwebpackplugin= Require (' Html-webpack-plugin '); Module.exports={entry:{main:"./src/index.js", Second:"./src/index2.js"}, output:{path:path.resolve (__dirname,' Dist '), FileName:"[Name]-[chunkhash]-bundle.js]}, module:{rules: [{test: /\.js$/, exclude: /(node_modules|bower_components)/, use: ' Babel-loader '  , Options: {presets: [' es2015 ' ]}}  ]}, plugins:[Newhtmlwebpackplugin ({Template:"./src/index.html"    })    ]}

(3) Packaging

(4) See effect (here from the file generated after packaging to see the effect)

  

See line 79th, our source file is const but here it becomes var. Babel-loader's job is to translate the new features of the new standard into the browser-supported notation, because these new features may not be supported by the browser, and with this transformation, we can use the new features with impunity (the word is great). For example, here we use the new features of ES6 Const,babel help us to turn to Var, so that all browsers support.

Let's take a look at module configuration. This fix has a rules attribute (2. x version), rules is an array in which you define a series of processing rules, each of which is an object. Each rule contains some configuration items, and the core has test to indicate what file to apply this rule to, use to specify the loader name to handle, and if more than one loader can be an array. Options is to provide some configuration items. There are many configuration items, such as exclude and so on, you can go to the official website, here do not expand, donuts.

5, summary

Webpack is a very powerful modular tool, she completely subvert the traditional local thinking mode, but instead of our project as a whole, effectively help us solve all kinds of dependency problems, to solve the problem of various resources conversion. This article uses several simple examples to explain the Webpack four core configuration item basic usage, only makes the use, Webpack is very powerful, has the rich loader and the plugin to be available for us to use, this article introduces the content is only its iceberg corner. Please refer to the official website for more information.

Finally, if you feel big ~ Bear classmate wrote the article to you some inspiration, please pay attention to, he and his doraemon will be very happy!!!

Reference:

    • https://webpack.js.org
    • http://www.css88.com/doc/webpack2/

Webpack you deserve-start with four core configurations

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.