One hour package Church--webpack Getting Started Guide

Source: Internet
Author: User
Tags 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, etc. as a module to use and processing.

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

You may not want to use it on your project, but there is no reason not to master it, as the examples shown on Github are already developed based on Webpack, such as React-bootstrap and Redux, on the most recent major (React-related) projects in the past.

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 in to see.

Advantages of Webpack

Its advantages can be categorized as follows:

1. Webpack is writing scripts in the form of CommonJS, but support for Amd/cmd is also comprehensive, facilitating code migration for older projects.

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

3. Easy to develop, can replace part of GRUNT/GULP work, such as packing, compression confusion, picture turn base64 etc.

4. Strong extensibility, perfect plug-in mechanism, especially to support React hot plug (see React-hot-loader) function to let a person in front of a bright.

Let's talk about 1th. In Amd/cmd mode, because the modules are loaded asynchronously, we routinely need to use the Define function to help us with callbacks:

function (Lib) {     function  foo () {        lib.log (' Hello world! ') );    }       return {        foo:foo    };});

In addition, in order to be compatible with CommonJS's wording, we can also write define:

Define (function  (require, exports, module) {    var somemodule = require ("Somemodule"  );     var anothermodule = require ("Anothermodule");        Somemodule.dotehawesome ();    Anothermodule.domoarawesome ();     function () {        somemodule.dotehawesome ();        Anothermodule.domoarawesome ();    };});

However, for Webpack, we can write the CommonJS form of grammar 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 ();     function () {        somemodule.dotehawesome ();        Anothermodule.domoarawesome ();    };

This way, it's easier to go with a callback to God's horse and say byebye~

But even if you keep 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

One. Installation

We routinely install it directly using NPM in the form of:

$ NPM Install Webpack-g

Of course, if the general project still relies on writing the Package.json package to be more humane:

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

Two. Configuration

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

Let's look at the example below:

varWebpack = require (' Webpack '));varCommonsplugin =NewWebpack.optimize.CommonsChunkPlugin (' Common.js '); Module.exports= {    //plug-in itemsplugins: [Commonsplugin],//Page Portal File configurationentry: {index:'./src/js/page/index.js '    },    //ingress file Output configurationoutput: {path:' Dist/js/page ', FileName:' [Name].js '}, module: {//Loader ConfigurationLoaders: [{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 ConfigurationsResolve: {root:' E:/github/flux-example/src ',//Absolute PathExtensions: [', '. js ', '. json ', '. Scss '], alias: {appstore:' Js/stores/appstores.js ', ActionType:' Js/actions/actiontype.js ', Appaction:' Js/actions/appaction.js '        }    }};

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

⑵entry is the page portal file configuration, output is the corresponding outputs of the configuration (that is, what the portal file will ultimately generate the name of the file, where to store), the syntax is roughly:

{    entry: {        "./page1",        // supports array form, will load all modules in the array, but with the last module as output        Page2: ["./entry1", "./entry2"]    },    output: {        "dist/js/page",        "[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 type of file needs to be handled using the loader:

module: {//Loader ConfigurationLoaders: [//. css files use Style-loader and css-loader to handle{test:/\.css$/, Loader: ' Style-loader!css-loader ' },            //. js files use 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 '},            //image files are processed using Url-loader, which is less than 8KB direct to Base64{test:/\. (png|jpg) $/, loader: ' url-loader?limit=8192 '}        ]    }

As above, "-loader" is actually can omit not to write, multiple loader between "!" To connect them.

Note that all loaders need to be loaded via NPM, and it is recommended to check their corresponding readme to see how they are used.

For the last Url-loader, it will convert the image referenced in the style to a module to be processed, and the loader needs to be installed first:

NPM Install Url-loader-save-dev

The parameters for configuration information "? limit=8192" means that all images less than 8kb are converted to Base64 form (in fact, it should be said that more than 8kb to use Url-loader to map to the file, otherwise to the data URL form).

You can click here to see the full list of loader.

⑷ finally is the resolve configuration, this piece is very well understood, directly writes the comment:

  resolve: { //  look for the module then find  root: ' e:/github/flux-example/src ', //  absolute path  //  auto extension file suffix name, means that we require module can omit not to write suffix name  extensions: [' ', '. js ', '. json ', '. Scss ' ], //  module alias definition, convenient for subsequent direct reference aliases, no longer need to write long addresses  Span style= "color: #000000;" > alias: {appstore:  ' js/stores/appstores.js ', //  Subsequent direct require (' AppStore ') can be  actiontype: ' js/actions/actiontype.js '  ' js/actions/appaction.js '  

For more detailed configuration of Webpack.config.js, refer to here.

Run Webpack

The execution of the Webpack is also simple, directly executed

$ webpack--display-error-details

, the following parameter "--display-error-details" is recommended, to facilitate error when you can consult more detailed information (such as the process of webpack looking for modules), so as to better locate the problem.

The other main parameters are:

$ webpack--config xxx.js   // use another profile (such as webpack.config2.js) to package  --watch   //  monitoring changes and automatically packaging  -P    // Compression Obfuscation script, this is very important! -d//Generate map Map file to tell which modules were eventually packaged      

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

Module Introduction

The above chit chat when so many configuration and execution methods, the following begins to talk about the normal page and script how to use Bai.

One. HTML

Directly on the page to introduce Webpack final generated page script can not write any more data-main or seajs.use:

<!DOCTYPE HTML><HTML><HeadLang= "en">  <MetaCharSet= "UTF-8">  <title>Demo</title></Head><Body>  <Scriptsrc= "Dist/js/page/common.js"></Script>  <Scriptsrc= "Dist/js/page/index.js"></Script></Body></HTML>

You can see that we don't even have to introduce the style, after all, when the script executes, it dynamically generates <style> and tags hit the head.

Two. JS

Each script module can write directly using CommonJS, and can directly introduce the non-compiled modules, such as JSX, sass, coffee, etc. (as long as you configure the corresponding loader in the webpack.config.js).

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

Require ('.. /.. /css/reset.scss ');//Load Initialization styleRequire ('.. /.. /css/allcomponent.scss ');//Load Component StylesvarReact = require (' React '));varAppwrap = require ('.. /component/appwrap ');//Loading ComponentsvarCreateredux = require (' redux ')). Createredux;varProvider = require (' redux/react ')). Provider;varStores = require (' AppStore '));varRedux =Createredux (stores);varAPP =React.createclass ({render:function() {        return (            <provider redux={redux}>                {function() {return<appwrap/>; }} </Provider>        ); }}); React.render (<app/>, document.body);

Is it all so simple? The following all kinds of have not, Webpack will help you to deal with.

Other

So far we have basically hand the use of webpack, here are some useful tips to add.

I. shimming

In Amd/cmd, we need to do shim processing of non-conforming modules (such as some plug-ins that return global variables directly), and we need to use Exports-loader to help:

{Test:require.resolve ("./src/js/tool/swipe.js"),  loader: "Exports?swipe"}

Then, when you need to refer to the module in the script, it's easy to use it:

Require ('./tool/swipe.js ')

Two. Custom Public module Extraction

At the beginning of the article we used the Commonschunkplugin plugin to extract common modules between multiple pages and package the module as Common.js.

But sometimes we want to be more personal, we can configure this:

varCommonschunkplugin = require ("Webpack/lib/optimize/commonschunkplugin"); Module.exports={entry: {p1:"./page1", p2:"./page2", p3:"./page3", AP1:"./admin/page1", AP2:"./admin/page2"}, Output: {filename:"[Name].js]}, plugins: [NewCommonschunkplugin ("Admin-commons.js", ["Ap1", "AP2"]),        NewCommonschunkplugin ("Commons.js", ["P1", "P2", "Admin-commons.js"])    ]};//<script>s Required://Page1.html:commons.js, P1.js//Page2.html:commons.js, P2.js//Page3.html:p3.js//admin-page1.html:commons.js, admin-commons.js, Ap1.js//admin-page2.html:commons.js, admin-commons.js, Ap2.js

Three. Standalone Package style file

Sometimes you might want your project's style to be wrapped up in a script, rather than as a. css, and then introduced in the page as a <link> tag. At this time we need extract-text-webpack-plugin to help:

    var webpack = require (' Webpack ');     var new webpack.optimize.CommonsChunkPlugin (' Common.js ');     var Extracttextplugin = require ("Extract-text-webpack-plugin");     = {        new extracttextplugin ("[name].css")],        entry: {        // ... Omit other configurations

After the final webpack executes, the style file is extracted:

Four. Cooperate with Grunt/gulp

With Gulp as an example, we can mix and match:

 gulp.task ("Webpack", function   (callback) { //  run Webpack   Webpack ({ //  configuration  }, function   (err, stats) { if  (Err) throw  new  gutil.        Pluginerror ("Webpack"  [Webpack] " //  output options  

Of course, we just need to write the configuration to Webpack ({...}) to go, no need to write webpack.config.js.

For more reference information, see: Grunt Configuration/Gulp configuration.

Five. React related

⑴ recommends installing and referencing the React module in the form of NPM install react instead of using the compiled react.js directly, so that the final compiled react portion of the script will reduce the size of 10-20 KB or so.

⑵react-hot-loader is a very easy-to-use react hot plug loading plug-in, through which can be implemented to modify-run the effect of synchronization, with Webpack-dev-server better!

Webpack-based introductory guide is here, I hope this article can help you, you can also refer to the following articles to get started:

Webpack Introductory Puzzle

Webpack-howto

Mutual Encouragement ~

One hour package Church--webpack Getting Started Guide

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.