Webpack Packaging and Gulp packaging tools detailed tutorials

Source: Internet
Author: User
Tags file url

30 minutes to teach you to learn Webpack combat

Read Catalogue

    • A: What is Webpack? What is his merit?
    • II: How to Install and configure
    • Three: Understanding the Webpack Loader
    • Four: Understanding the use of the Less-loader loader
    • V: Understanding the meaning of the Babel-loader loader
    • Six: Understand the next webpack of several commands
    • Seven: Webpack packaging for multiple module dependencies
    • Eight: How to package a style file independently
    • Nine: How to package multiple resource files
    • Ten: About the packaging of pictures
    • 11: React Development Artifact: React-hot-loader
Back to Top

What is Webpack? What is his merit?

First of all, for many just contact Webpack people, will certainly ask Webpack is what? What advantages does it have? Why should we use it? With these questions, let's summarize the following:

Webpack is a front-end tool that allows modules to be loaded, preprocessed, packaged, and capable of grunt or gulp all basic functions. The advantages are as follows:

    1. Supports COMMONJS and AMD modules.
    2. Support for a number of module loader calls, can make the module loader flexible customization, such as the Babel-loader loader, which allows us to use the ES6 syntax to write code.
    3. Configuration can be packaged into multiple files, effectively leveraging the browser's caching capabilities to improve performance.
    4. Using the module loader, you can support sass,less and other processors for packaging and support static resource styles and images for packaging.
    5. More ... etc... With these questions we slowly learn webpack.
Back to Top

II: How to Install and configure

First of all, my project directory structure is: The file is called Webpack, there is only one main.html, the code is as follows:

<!doctype html>

There is also a folder src, the folder contains two JS files, react.min.js source files and main.js files, main.js source code as follows:

/* Content Area module code */var Contentmode = React.createclass ({        render:function () {            return (                <div classname=) Contentmode ">                    <div class=" Contents ">{this.props.contents}</div>                    {This.props.children}                </div>            )        }); * Page DIV package above three modules */var page = React.createclass ({    render:function () {        return (            <div classname= "homepage ">                <contentmode  contents =" Longen ">this is one comment</contentmode >                <contentmode  contents = "Longen2" >this is the Comment</contentmode >            </div>            )        });/* Initialize to content container */react.render (       react.createelement (page,null), document.getElementById ("content"));

The code is react.js code, is react.js to learn one of the code copied over in order to demonstrate;

The installation steps are as follows:

    1. Generate Package.json files;

First we need to generate the Package.json file under the root directory, and we need to go to the root directory of the project file to execute the following command: NPM Init

The Package.json file will be generated in the root directory, as shown below, by a question and answer method:

2. Webpack by Global Installation

The Execute command is as follows: NPM install-g Webpack as shown below:

The Node_modules folder generated under the C drive will contain webpack, and we can use the Webpack command at this point;

3. Configure Webpack

Each directory must have a webpack.config.js, its role is like gulpfile.js, or Gruntfile.js, is a project configuration, tell Webpack what needs to do.

Here is my webpack.config.js code as follows:

Module.exports = {  entry: "./src/main.js",  output: {    filename: "Build/build.js"  },  module: {    Loaders: [       //.css file uses Style-loader and Css-loader to process      {test:/\.css$/, Loader: ' Style!css '},      //.js file use Jsx-l Oader to compile processing      {test:/\.js$/,    loader: "Jsx-loader"}    ]  },  resolve: {    extensions: [', '. js ', '. Jsx '  },  plugins: []};

entry is a portal file on the page, such as the entry file on my side main.js

output: refers to the page through the Webpack packaging generated by the target file where to go, my side is in the root directory to generate a build folder, the folder has a build.js file;

Resolve: defines the configuration of the parsing module path, commonly used is extensions; Can be used to specify the suffix of the module, so that the introduction of the module does not need to write suffixes, will be automatically complete.

Plugins: defines the plug-ins that need to be used, such as commonsplugin to extract common parts when packaging multiple entry files, and generate Common.js;

module.loaders: is the file loader, for example, we react need to introduce the page Jsx JS source code to the page, and then use the syntax, However, by Webpack packaging, you do not need to introduce jsxtransformer.js, see the above loader, such as Jsx-loader Loader is representative of Jsxtransformer.js, there are style-loader and Css-loader loader; We need to introduce it to the project by command, so we need to generate the following command;

The Jsx-loader loader npm Install Jsx-loader--save-dev is as follows:

The Style-loader loader npm Install Style-loader--save-dev is as follows:

The Css-loader loader npm Install Css-loader--save-dev is as follows:

Local installation Webpack Execute command: NPM install Webpack--save-dev

We'll simply put the gulp in the global installation and in the project installed in the local installation, later useful ~

The Gulp global installation of NPM Install-g Gulp is as follows:

Within the project file, the Gulp Local installation uses the command NPM install Gulp--save-dev as follows:

Therefore, the following files are generated under our folder Node_modules:

Now let's execute the order webpack; As shown below:

To build a build folder in the root directory, Build.js looks like this:

We can also use the following command: Webpack--display-error-details command execution, so that the convenience of error when you can view more detailed information, such as the following:

Now let's refresh the next page and see the following:

You can see the page rendering, and then we'll look at the request in the page:

You can see that there is only one file react.min.js source file and Build.js we just generated the Build.js file, so after we have packaged through Webpack, we now no longer need to introduce jsxtransformer.js as before. We can also look at the build.js generated in those JS, here is not affixed to the code, you can look at the ~

The above is packaged using Webpack; Now let's take a look at the second option to package ~

Use Gulp to package

We know to use Gulp to pack, then we need to create a new gulpfile.js in the root directory;

So our side gulpfile.js the source code as follows:

var gulp = require (' gulp '), var webpack = require ("Gulp-webpack"), var webpackconfig = require ("./webpack.config.js"); Gulp.task (' Webpack ', function () {    var myconfig = object.create (webpackconfig);    Return gulp.        src ('./src/main.js ')        . Pipe (Webpack (myconfig))        . Pipe (Gulp.dest ('./build '));}); /Register Default task Gulp.task (' Default ', [' webpack ']);

Then the Webpack.config.js code becomes as follows:

Module.exports = {  entry: "./src/main.js",  output: {    filename: "Build.js"  },  module: {    Loaders: [       //.css file uses Style-loader and Css-loader to process      {test:/\.css$/, Loader: ' Style!css '},      //.js file using JS X-loader to compile processing      {test:/\.js$/,    loader: "Jsx-loader"}    ]  },  resolve: {    extensions: [', '. js ', '. Jsx '  },  plugins: []};

, and then enter gulp on the command line to generate the Build/build.js, as shown below:

The code on GitHub is as follows: https://github.com/tugenhua0707/webpack/can download the compressed package and run it.

Back to Top

Three: Understanding the Webpack Loader

Webpack provides a set of loaders, such as Css-loader,less-loader,style-loader,url-loader, for loading different files into a JS file, such as Url-loader for loading in JS png/ JPG format picture file, Css/style loader for loading CSS files, Less-loader loader is to compile less to CSS file;

Configuration Loader

Module.exports = {  entry: "./src/main.js",  output: {    filename: "build.js",    path: __dirname + '/assets/ ',    publicpath: '/assets/'  },  module: {    loaders: [      {test:/.css$/, Loader: ' Style!css '},      { Test:/. (png|jpg) $/, loader: ' url-loader?limit=8192 '}    ]  }  Resolve: {extensions: [', '. js ', '. Jsx '],//module alias definition, Easy to follow the direct reference alias, do not need to write long address alias: {    A: ' Js/assets/a.js ',  //followed by direct reference to require ("a") can refer to module    B: ' Js/assets/b.js ',    c: ' Js/assets/c.js '}  ,  plugins: [Commonsplugin, New Extracttextplugin ("[Name].css")]}

module.loader: where test is a regular expression, use the appropriate loader for the matching file name.

/.css$/will match the Xx.css file, but it does not apply to Xx.sass or xx.css.zip files.

Url-loader It will convert the image referenced in the style to the module to handle; The parameter "? limit=8192" of the configuration information means that all pictures less than 8kb are converted to Base64 form.

The entry file for the entry module. All the files in the dependency array are packaged sequentially, and each file is dependent on the recursive lookup until all modules are packed;

Output: The input file of the module, which has the following parameters:

FileName : The file name after packaging

path: The absolute path where the package file is stored.

Publicpath: The Access path when the Web site runs.

relolve.extensions: The suffix name of the auto-extension file, such as when we are in the Require module, we can not write the suffix name.

relolve.alias: module alias definition, easy to follow the direct reference alias, no need to write long address

plugins is a plug-in item;

Back to Top

Four: Understanding the use of the Less-loader loader

We first understand the next Less-loader loader, the other sass-loader is also a meaning, this side will not be all the preprocessing of the CSS to explain, Less-loader loader is the CSS code into the style tag, dynamically inserted into the head tag inside Let's start by looking at the structure of my project as follows:

We now have a main.less code below the CSS file as follows:

@base: #f938ab; html,body {  background: @base;}

SRC file has a main.js file when this JS file is the entry file; The code inside is as follows:

Css

Require ('.. /css/main.less ');

The Webpack.config.js code is configured as follows:

Module.exports = {  entry: "./src/main.js",  output: {    filename: "build.js",    path: __dirname  },  module: {    loaders: [      //.css file uses Style-loader and Css-loader to process      {        test:/\.less$/,        loader: " Style!css!less "      }    ]  },  resolve: {    extensions: [', '. js ', '. Jsx ']  },  plugins: []} ;

The Gulpfile.js code is as follows (note: This file can either be used to run the package using Gulp, or it can be packaged directly using Webpack, either).

var gulp = require (' gulp '), var webpack = require ("Gulp-webpack"), var webpackconfig = require ("./webpack.config.js"); Gulp.task (' Webpack ', function () {    var myconfig = object.create (webpackconfig);    Return gulp.        src ('./src/main.js ')        . Pipe (Webpack (myconfig))        . Pipe (Gulp.dest ('./build '));}); /Register Default task Gulp.task (' Default ', [' webpack ']);

So we need to install Style-loader Css-loader and Less-loader as follows:

After the installation is complete, we look at our project's root directory node_modules with the following several files:

Once configured, we will run the Gulp or Webpack command after entering the project, In the build folder will generate Build.js, this JS is dynamically generated style label and explain the normal CSS inserted into the document head tag; we can run the next page and look at the code below:

So we can see that the page is in effect; for a better demo test, I put the code on GitHub, which I can download and run under both: Https://github.com/tugenhua0707/webpack-less-loader

Back to Top

V: Understanding the meaning of the Babel-loader loader

The Babel-loader loader can convert ES6 code into ES5 code, which allows us to use ES6 now; before we use it, we need to install Babel-loader

Execute command: NPM install Babel-loader–save-dev is as follows:

As soon as the installation is complete, we will generate the file in the root directory node_modules as follows:

Now we can moudle.loaders configuration loader in Webpack.config.js, the following code:

{test:/\.js$/, Loader: ' Babel ', exclude: '/node_modules/'}

So the Webpack.config.js code becomes as follows:

Use Webpack Packaging module.exports = {  entry: "./src/main.js",  output: {    filename: "build.js",    Path: __ DirName  },  module: {    loaders: [      {test:/\.js$/, Loader: ' Babel ', exclude: '/node_modules/'}    ]  },  resolve: {    extensions: ["', '. js ', '. Jsx ']  },  plugins: []};

Let's take a look at the directory structure in my project as follows:

We're looking at the src source file with the following files

React.min.js is React source, this does not say, Bind.js ES6 code as follows:

ES6 syntax Let LOADER = true; Module.exports = LOADER;

Main.js is the entry file for the page, the code is as follows:

Let loader = require ('./bind '); Console.log (loader);

Let is the ES6 syntax equivalent to the meaning of the var definition variable in JS, and then print to true in the bind module;

The final execution gulp is as follows:

Print true in the console; I put the source on GitHub, and the students who need it can download it on their own, as follows GitHub (I haven't used GitHub for 2 years, and now I'm using it again, in order to demonstrate the demo problem better); https://github.com/ Tugenhua0707/webpack-babel-loader

Back to Top

Six: Understand the next webpack of several commands

    1. Webpack//The most basic way to start webpack
    2. WEBPACK-W//provide watch method; package updates in real time
    3. WEBPACK-P//Compress the packaged files
    4. WEBPACK-D//provide source map, convenient mode code

Let's get down to the next webpack-w.

As shown below:

For example, I add a little bit of code in the JS file, after saving, then refresh the page can see the code to take effect, no need to rerun Webpack or gulp, using WEBPACK-W can be packaged in real time. The meaning of webpack-p is to compress the files after they are packaged, such as when I used chrome to look at the packaged code as follows:

As you can see, the code is uncompressed, but when I run the webpack-p command on the console command line, it looks like this:

Let's go back to the console and look at the code as it has been compressed, as shown here:

Webpack-d is available in the source code before the compression of the user-friendly mode, as follows:

When I run as shown above, let's take a look at what the code has just been compressed into. As shown below:

As the above code can see our compressed code, by running the webpack-d command, you can restore the uncompressed code, so that the convenience of our online code.

Let's take a look at the directory where the map file will be generated as follows:

Back to Top

Seven: Webpack packaging for multiple module dependencies

We learned from the beginning that Webpack supports the packaging of the COMMONJS and AMD two modular mechanisms, so we are now going to use the COMMONJS and AMD mechanisms in the code to do a demo;

The SRC source file adds module1.js module2.js module3.js code, respectively, as follows:

Module1.js code://Module1.jsrequire (["./module3"], function () {    console.log ("Hello webpack!");}); The Module2.js code is as follows://Module2.js, using the COMMONJS mechanism export Package Module.exports = function (A, b) {    return a + b;} The Module3.js code uses the AMD mechanism//module3.js, using the AMD module mechanism define (['./module2.js '], function (sum) {    return Console.log ("1 + 2 =" + SUM (1, 2);}); The entry file Main.js code is as follows: Require ("./module1");

We can run the next Webpack after generating the following files in the root directory:

Where the 1.build folder is COMMONJS generated inside is the COMMONJS code; we'll look at the page code below to see:

We continue to view the console output as follows:

So far we can see that Webpack packaging can support COMMONJS modules and AMD modules.

The specific code can see the source on my GitHub:

Https://github.com/tugenhua0707/webpack-multi-module-depend

Back to Top

Eight: How to package a style file independently

Sometimes we don't want to play the style in the script, but want to separate CSS out, and then in the page Sisu chain CSS, this time we need to extract-text-webpack-plugin to help: We first need to install Extract-text-webpack-plugin: The following: NPM install Extract-text-webpack-plugin–save-dev is as follows:

It will then generate the following in the directory:

Now we need to look at the Webpack.config.js configuration into the following:

var extracttextplugin = require ("Extract-text-webpack-plugin");//Use Webpack package Module.exports = {  entry: "./src/ Main.js ",  output: {    filename:" Build.js "  },  module: {    loaders: [      //.css file uses Style-loader and Css-loader to process      {        test:/\.less$/,        loader:ExtractTextPlugin.extract (            ' css?sourcemap! ' +            ') Less?sourcemap '        )      }    ]  },  resolve: {    extensions: [', '. js ', '. Jsx '  },  // Inline CSS extracts to a separate styles CSS  plugins: [New Extracttextplugin (' Styles.css ')]};

After the configuration is completed we gulp run, in the Build folder will generate 2 files, one is the Build.js processing module of the file another is our styles.css, we look at the following:

This is followed by the introduction of HTML files:

<!doctype html>

Run the following on the page to see the effect: We can look at the number of requests:

The specific code demo can be seen on my GitHub as follows:

Https://github.com/tugenhua0707/extract-text-webpack-plugin

Note: Node_modules module is not uploaded up, git upload does not go up, always prompt filename too long error, so there is no upload, you need to install the following modules locally:

Back to Top

Nine: How to package multiple resource files

When we develop the page, sometimes need to have a number of portal files, so that the file is loaded on demand, so you can use the cache to improve performance, then we need to configure it next? Now let's continue with the demo, now for example my project file structure is as follows:

We look directly at the Webpack.config.js configuration code into the following:

Module.exports = {  entry: {     "main": "./src/main.js",     "index": "./src/index.js"  },  output: {    FileName: "[Name].bundle.js"  }};

From the configuration code above we can see that entry is now an object, and the object name is key as the FileName property of the following output [name]. Of course entry can also be an array.

So we can generate 2 portal files under the build file directly gulp run as shown above: The GitHub source address is as follows:

Https://github.com/tugenhua0707/webpack-many-page

Now we can introduce different portal files according to different pages to implement loading files on demand.

Back to Top

Ten: About the packaging of pictures

We know that the images are loaded using Url-loader, and we can both have the properties of the URL in the CSS file, as follows:

#content {    width:170px;    height:60px;    Background:url ('.. /images/1.jpg ') no-repeat;}

We can also directly assign values to the SRC attribute of the element require. The following code:

var img = document.createelement ("img"); IMG.SRC = require (".. /image/1.jpg "); Document.body.appendChild (IMG);

My side directly to the first type in the CSS file URL attributes to package;

First take a look at the directory structure of my project as follows:

The CSS file Main.css code is as follows:

#content {    width:170px;    height:60px;    Background:url ('.. /images/1.jpg ') no-repeat;}

JS file Main.js code is as follows:

Require ('.. /css/main.css ');

The Webpack.config.js configuration file code is as follows:

Use Webpack Package Module.exports = {    entry: {     "main": "./src/main.js"  },  output: {    path: './build/',    filename: "Build.js"  },  module: {    loaders: [      {test:/.css$/, Loader: ' Style!css '},      { Test:/. (png|jpg) $/, loader: ' url?limit=8192 '}    ]  };

Run Webpack directly to generate the build directory, which generates 2 files under the build directory one is the picture is packaged, the other one is build.js. Then we run the page in the pages, found that there is a problem, as follows:

The URL of the page call picture is the root directory, not my package after the build folder, so it will cause the picture path can not find the problem, so there is a little unfinished task, hope that the child boots interested can help to complete ~ But the picture is indeed already packed, for convenience, We still offer the GitHub source code! As shown below:

Https://github.com/tugenhua0707/webpack-url-loader

Webpack Packaging and Gulp packaging tools detailed tutorials

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.