Handy Packaging Tools Webpack

Source: Internet
Author: User
Tags unique id css preprocessor

< what is webpack>

Webpack is a module packager, any static resources (js, css, pictures, Etc.) can be regarded as modules, and then can be interdependent between the modules, through the Webpack module processing, can be packaged into the static resources we Want.

Gulp Packaging is the js, css, pictures and other packaging separately, but Webpack is all the static resources packaged together, so a request can Be.

Features of <webpack >

• Support Commonjs (require) and AMD modules, which means you can migrate old items without pain

• Support module loader and plug-in mechanism to flexibly customize the module, especially babel-loader, effectively support ES6

• Can be configured to package into multiple Files. Effectively leverages the Browser's caching capabilities to improve Performance. To pull out common things, such as Jquery.

• Treat static resources like style files and pictures as modules for Packaging. With loader loader, support sass, less CSS preprocessor

• Built-in source map for easy commissioning even when packaged together

Installation of <webpack >

1, First Global Installation

NPM Install Webpack-g

Webpack-w provides a watch method to package updates in real time

Webpack-p compressing a packaged file

WEBPACK-D provides sourcemap for easy commissioning

Webpack--config with a config as a package

Webpack--help More Commands

2, then Local installation

NPM init initializes first, generating Package.json. Re-install so that you can easily view dependent files

NPM Install Webpack--save-dev development-dependent, Some packaging tools, such as gulp, webpack, etc. are development-dependent, on-line do not need

<webpack First Experience >

For example, if all files are packaged into bundle.js, you will introduce bundle.js in the page

Webpack./entry.js bundle.js   //compile Entry.js and package to Bundle.js

< module dependencies >

Webpack parses the entry file, parsing the individual files that contain the dependencies

• These files (modules) are packaged in the Bundle.js file

Webpack assigns a unique ID to each module and passes the ID index and Access module

• The Entry.js code is executed first when the page starts, and the other modules are lazy-loaded at require

<loader Loader >

Webpack itself can only handle JavaScript modules, and if you want to work with other types of files, you need to use loader to convert

· Loader can be understood as a converter for modules and resources that can convert modules of any type (jsx, jade, etc.)

· Loader can be chained by pipeline, each loader can convert the resource into any format and pass it to the next loader, but the last loader must return JavaScript because the Webpack only knows Js. Different files, the use of loader is not the same

· Loader can accept parameters to pass configuration items to Loader.

· Loader can be installed via NPM

· Loader can bind different loaders by file name extension (or regular Expression)

< loading CSS files >

Installation of two LOADER:NPM install Css-loader Style-loader

• First consider style.css as a module

• Use Css-loader to read it

• Embed it in HTML with Style-loader

Introduced in Entry.js:

Require ("css!. /style.css ")// equivalent to require (" css-loader!. Style.css "). because The-loader of Css-loader is Fixed,-loader is generally omitted.
/* The original CSS is read through Css-loader and needs to be passed to Style-loader. So the require also needs to be supplemented as follows: */
Require ("style!css!. /style.css ")
The equivalent of a stream in gulp, flowing from right to left

Execute again

Webpack./entry.js Bundle.js   
Compiling the style files introduced by Entry.js to Bundle.js

< loading picture url-loader>

Url-loader will convert the picture referenced in the style into a module to handle

NPM Install Url-loader

The parameter of limit means that when the image size is smaller than this limit, the Base64 encoded image is automatically Enabled.

< configuration files >

Webpack can be executed at the time of the specified configuration file

• The webpack.config.js in the current directory is executed by default and is automatically found when the Webpack is Entered.

• The configuration file is a Node. JS module that returns a json-formatted configuration information object

• Add a configuration file, then execute webpack--progress--colors It's ready.

The configuration file format is:

varWebpack = Require ("webpack") Module.exports={entry:"./entry.js",//Specifies the package entry file, each Key-value pair, is a portal file. output:{//Configure Packaging Resultspath:__dirname,//folder that defines the outputFilename: "bundle.js"//defines the name of the package result file}, module:{//defines the load logic for the moduleloaders:[//defines a series of loaders{test:/\.css$/,loader: "style!css"},//when a file that needs to be loaded matches the regular of ' Test ', the corresponding loader is used{test:/\. (png|jpg) $/,loader: "url?limit=40000"}, {test:/\.js?$/,loader: "babel", exclude:/node_modules/,query:{compact:false, presets:[' es2015 '}}//for all JS files, use Babel-loader                                                                   //to load, ignore node_modules below                                                                  //the JS File. Query represents the parameter, which is equivalent to                                                                 //url-loader's? Form. ]}, plugins:[//the use of Plug-ins is typically specified in the Webpack configuration information Plugins option, and we can insert some information into the header of the generated package file     NewWebpack. Bannerplugin ("//ding is learning webpack"),//Add comment information to the file header after packaging     NewWebpack.optimize.CommonChunkPlugin ("common.js")//separate the public parts of multiple modules and load them separately.], resolve:{alias:{//alias, which is the role of redirecting a User's request to another pathJquery: "./js/jquery.js"//in this way, only require ("jquery") is needed in the components that use jquery, and no longer need to step up to find the location of jquery     } }}

  expose, If you want to use packaged jquery in the foreground, you need to expose jquery, first install the module NPM install Expose-loader--save-dev

Eg: exposes $ as a variable that is aliased to jquery into the global context require ("expose?$!jquery"), and when you introduce jquery, bind the jquery object to the $ on window

  The entry property can make an object, and the object name is key, as the name of the FileName property of the following output

entry:{

Bundle1: "./entry1.js",

Bundle2: "./entry2.js"

}

output:{

path:__dirname,

Filename: "[name].js"//[name] here means Bundle1 and bundle2

}

If Bundle1 and Bundle2 both contain functionally identical parts, you can extract this part.

  • Public Modules. We use plugins to intelligently extract public parts to provide cache reuse for our browsers

plugins:[

New Webpack.optimize.CommonChunkPlugin ("common.js")//the Public part of multiple modules, separately extracted, loaded separately

]

We need to manually load the Common.js on the html, and it must be loaded first

< using es6>

NPM Install Babel-core--save-dev

NPM Install Babel-loader--save-dev

NPM Install babel-preset-es2015

<webpack-dev-server>

NPM Install Webpack-dev-server-g

After installation, execute webpack-dev-server, start an express service in the current directory, automatically packaged and refreshed in real time

< advantages of Gulp compared to Webpack >

Webpack can not do automatic deployment and code checking, Webpack is just a packaging tool. So you can use Gulp and webpack to mix with the method

var gutil = require ("gulp-util"); var webpack = require ("webpack"); var webpackconfig = require ("./webpack.config.js"); gulp.task ("webpack",function( Callback) {   var myconfig = object.create (webpackconfig);   Webpack (myconfig,function(err,stats) {      callback ();   })}) Gulp.task ("default",function() {gulp.watch ("./**", ["webpack"]);})

Handy Packaging Tools Webpack

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.