Webpack Packaging Process __web

Source: Internet
Author: User
Tags base64 call back define function

What is Webpack.

Webpack is the most recent one of the most fire module loader and packaging tools, it can be a variety of resources, such as JS (including JSX), coffee, style (including less/sass), pictures and so on as a module to use and deal with.

We can introduce modules directly in the form of require (XXX), even though they may need to be compiled (such as JSX and sass), but we don't have to spend too much time on it because Webpack has a variety of sound loaders (loader) that are silently handling these things, This is what we'll talk about later.

You may not want to use it on your project, but there is no reason not to master it, because in the recent Github major (react-related) projects, the samples shown in their warehouses have been developed based on Webpack, such as React-boostrap and redux.

Webpack's official website is http://webpack.github.io/, the document address is http://webpack.github.io/docs/, want to have a more detailed understanding of it can point inside to see.

Advantages of Webpack

Its advantages can mainly be categorized as follows:

1. Webpack is written in the form of Commonjs script drops, but the amd/cmd support is also very comprehensive, facilitate the old project code migration.

2. It is not only JS that can be modularized.

3. The development of convenient, can replace part of the GRUNT/GULP work, such as packaging, compression confusion, picture transfer base64 and so on.

4. Expansibility, perfect plug-in mechanism, especially to support the React hot plug (see React-hot-loader) The function of the people before the light.

Let's talk about the 1th. In Amd/cmd mode, given that the module is loaded asynchronously, we routinely need to use the Define function to help us with the callback:

define ([' package/lib '], function (lib) {
 
    function foo () {
        lib.log (' Hello world! ');
    } 
 
    return {
        Foo:foo
    };
};

In addition, in order to be compatible with the COMMONJS, we can also write the define:

Define (function (Require, exports, module) {
    var somemodule = require ("Somemodule");
    var anothermodule = require ("Anothermodule");    

    Somemodule.dotehawesome ();
    Anothermodule.domoarawesome ();

    Exports.asplode = function () {
        somemodule.dotehawesome ();
        Anothermodule.domoarawesome ();;};

However, for Webpack, we can write the syntax of COMMONJS form directly above, without any define (after all, the final module is packaged together, Webpack will eventually automatically add its own loader):

    var somemodule = require ("Somemodule");
    var anothermodule = require ("Anothermodule");    

    Somemodule.dotehawesome ();
    Anothermodule.domoarawesome ();

    Exports.asplode = function () {
        somemodule.dotehawesome ();
        Anothermodule.domoarawesome ();
    };

So the code is naturally simpler, with the call back to God's horse byebye~

However, even if you retain the define before the writing is also can drop, after all, webpack compatibility is very good, convenient for your old project module directly migrated over.

Installation and Configuration

I. Installation

We routinely install it directly using NPM:

$ NPM Install Webpack-g

Of course, if the regular project is still to rely on writing Package.json package to more humane:

$ NPM Init
$ NPM Install Webpack--save-dev

Two. Configure

Each project must be configured with a webpack.config.js that acts as a regular gulpfile.js/gruntfile.js, a configuration item that tells Webpack what it needs to do.

Let's look at the example below:

var webpack = require (' Webpack ');

var commonsplugin = new Webpack.optimize.CommonsChunkPlugin (' Common.js '); Module.exports = {//plugin item plugins: [Commonsplugin],//Page entry file Configuration entry: {index: './src/js/page/inde 
        X.js '},///import File output config: {path: ' dist/js/page ', filename: ' [name].js '}, module: {  Loader configuration loaders: [{test:/\.css$/, Loader: ' Style-loader!css-loader '}, {test:
            /\.js$/, loader: ' Jsx-loader?harmony '}, {test:/\.scss$/, Loader: ' Style!css!sass?sourcemap '}, {test:/\. (png|jpg) $/, loader: ' url-loader?limit=8192 '}]},//Other solution configuration resolve: {root: ' E:/github/flux -example/src ',//absolute path extensions: [', '. js ', '. json ', '. Scss '], alias: {App Store: ' Js/store
        S/appstores.js ', ActionType: ' Js/actions/actiontype.js ', appaction: ' Js/actions/appaction.js ' }
    }
};

⑴plugins is a plug-in item, where we use a commonschunkplugin plug-in that extracts the common script portion of multiple portal files and then generates a common.js to facilitate reuse between multiple pages.

The ⑵entry is the page entry file configuration, output is the corresponding export item configuration (that is, the entry file will eventually generate what name of the file, where to store), the syntax is roughly:

{
    entry: {
        page1: './page1 ',
        //Support array form, all modules in the array will be loaded, but with the last module as output
        page2: ["./entry1", "./entry2"]
    },
    output: {
        path: ' dist/js/page ',
        filename: ' [name].bundle.js '
    }
}

The code eventually generates a page1.bundle.js and page2.bundle.js and is stored under the./dist/js/page folder.

⑶module.loaders is the most critical piece of configuration. It tells Webpack that each file needs to be handled using what loader:

    Module: {
        //loader configuration
        loaders: [
            //.css file uses Style-loader and Css-loader to process
            {test:/\.css$/, loader: ' Style-l Oader!css-loader '},
            //.js file uses Jsx-loader to compile processing
            {test:/\.js$/, Loader: ' Jsx-loader?harmony '},
            //.scss Files are compiled with Style-loader, Css-loader, and Sass-loader
            {test:/\.scss$/, Loader: ' Style!css!sass?sourcemap '},
            // Picture files are processed using Url-loader, which is less than 8kb directly to Base64
            {test:/\. png|jpg) $/, loader: ' url-loader?limit=8192 '}
        ]
    }

As above, "-loader" is actually can omit not write, multiple loader between use "!" Connect them.

Note that all loaders need to be loaded via NPM and suggest checking their corresponding readme to see how to use them.

For the last url-loader, it converts the picture referenced in the style to a module, which needs to be installed first:

NPM Install Url-loader-save-dev

The parameter "? limit=8192" of the configuration information indicates that all pictures less than 8kb are converted to Base64 form (in fact, it should be said that more than 8kb is used Url-loader to map to the file, otherwise it will be converted to the data URL form).

⑷ finally is the resolve configuration, this piece is very good to understand, directly write the annotation:

    Resolve: {
        ////Find module From here start looking for
        root: ' e:/github/flux-example/src ',///absolute path//
        auto extension file suffix name, means that our require module can omit not to write suffix name
        extensions: [', '. js ', '. json ', '. Scss '],
        //module alias definition, facilitate subsequent direct reference alias, no longer need to write long address
        alias : {
            App Store: ' Js/stores/appstores.js ',//follow-up direct require (' App Store ') can
            ActionType: ' Js/actions/actiontype.js ' ,
            appaction: ' Js/actions/appaction.js '
        }
    }

A more detailed configuration of webpack.config.js can be referenced here.

Run Webpack

The execution of Webpack is also simple, direct execution

$ webpack--display-error-details

Then, the following parameter "--display-error-details" is recommended Plus, the convenience of error can refer to more detailed information (such as Webpack search module process), so that better positioning to the problem.

The other main parameters are:

$ webpack--config xxx.js   //Use another configuration file (such as webpack.config2.js) to pack

$ webpack--watch   //monitor changes and automatically pack

$ Webpack-p    //Compression obfuscation script, this is very very important.

$ webpack-d    //Generate map Map file to tell which modules were eventually packaged where

The-p is a very important parameter, once an uncompressed 700kb file, compressed directly down to 180KB (mainly the style of the sentence on the exclusive line of script, resulting in uncompressed scripts become very large).

Module Introduction

With so many configuration and execution methods on it, let's start with how the usual pages and scripts are used, says chit chat when.

One. HTML

Directly in the page to introduce Webpack final generated page script, no longer write what data-main or seajs.use:

<! DOCTYPE html>

We can see that we don't even have to introduce the style, after all, the script will dynamically generate <style> and tag into the head when executing.

Two. JS

Each script module can be written directly using COMMONJS, and can be directly introduced into the precompiled modules, such as JSX, sass, coffee, etc. (as long as you have configured the corresponding loader in the webpack.config.js).

Let's take a look at the pre-compile page entry file (index.js):

require ('.. /.. /css/reset.scss '); Load initialization style require (' ... /.. /css/allcomponent.scss ');
Load component style var react = require (' react '); var appwrap = require ('.. /component/appwrap ');
Load component var Createredux = require (' redux '). Createredux; var Provider = require (' Redux/react ').
Provider;

var stores = require (' App Store ');

var redux = Createredux (stores);
                var App = React.createclass ({render:function () {return (<provider redux={redux}>
            {function () {return <appwrap/>;}}}
    </Provider>);

}
}); React.render (<app/>, document.body); 

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.