Webpack an hour to get started

Source: Internet
Author: User
Tags base64 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:

define ([' package/lib '], 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 ();    Exports.asplode = 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 ();    Exports.asplode = 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:

 var webpack = require (' Webpack '); var commonsplugin = new Webpack.optimize.CommonsChunkPlugin (' Common.js ');     Module.exports = {//Plugin entry plugins: [Commonsplugin],//Page entry file Configuration entry: {index: './src/js/page/index.js ' },//ingress file output config: {path: ' dist/js/page ', filename: ' [name].js '}, module: {//load Device 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-examp Le/src ',//absolute path extensions: [', '. js ', '. json ', '. Scss '], alias: {appstore: ' Js/stores/appstor Es.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: './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 type of file needs to be handled using the 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 '},            // The picture file is 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 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: {        //find module words from here to 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 need to write long address        alias : {            appstore: ' js/stores/appstores.js ',//follow direct require (' AppStore ') to            actiontype: ' Js/actions/actiontype.js ' ,            appaction: ' 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 $ webpack--watch   //monitor changes and automatically package $ webpack-p    / /compression Obfuscation script, this is very very important! $ webpack-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>

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 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 (' AppStore '); var redux = Createredux (stores); var App = 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:

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:

var commonschunkplugin = 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: [        new Commonschunkplugin ("Admin-commons.js", ["Ap1", " AP2 "]),        new Commonschunkplugin (" 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 commonsplugin = new Webpack.optimize.CommonsChunkPlugin (' Common.js ');    var extracttextplugin = require ("Extract-text-webpack-plugin");    Module.exports = {        plugins: [Commonsplugin, New Extracttextplugin ("[Name].css]"),        entry: {        //... Omit other configurations

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

Four. Using cdn/remote Files

Sometimes we want some modules to go to the Cdn and mount it in the form of <script>, but want to be able to use it in the Webpack module.

At this point we can use the Externals property in the config file to help:

{    externals: {        //require ("jquery") is referenced from external module        //corresponding global variable jquery "        jquery": "jquery"    }}

It is important to be aware that CDN files must be introduced before the Webpack package file is introduced.

We can also use script.js to load our modules in scripts:

var $script = require ("Scriptjs"); $script ("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function () {  $ (' body '). HTML (' It works! ')});

Five. 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", err);        Gutil.log ("[Webpack]", stats.tostring ({            //Output Options        });        Callback ();    });

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.

Six. 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 an hour to get started

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.