I. Introduction 1, 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-boostrap 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.
2, The 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. The extensibility is strong, the plug-in mechanism is perfect, especially supports the React hot plug function to let the person in front of a bright.
second, Installation and configuration1. 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
The Webpack,webpack command can be used globally with the command Above.
2. 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.
Using Webpack in your project
Add a Package.json profile with NPM $ NPM init install Webpack plug-in and configure Webpack to Package.json file $ npm Install Webpack--save-dev We 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).
⑷ finally is the resolve configuration, this piece is very well understood, directly writes the Comment:
resolve: { // find the module then start looking for root: ' e:/github/flux-example/src ', // absolute path // auto-extend file suffix name, means that we require module can omit not to write suffix name extensions: [' ', '. js ', '. json ', '. scss ' ], // module alias definition to facilitate subsequent direct reference aliases without having to write long addresses alias: {appstore: ' js/stores/appstores.js ', // Subsequent direct require (' AppStore ') can be actiontype: ' JS/ACTIONS/ACTIONTYPE.J S ' ' js/actions/appaction.js ' } }
For more detailed configuration of webpack.config.js, refer to Here.
third, running 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)
Iv.
Introduction of modules 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. JSEach 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.
FiveotherSo far we have basically hand the use of webpack, here are some useful tips to add.
I. shimmingIn 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 extractionAt 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 fileSometimes 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. using cdn/remote filesSometimes 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 a global variable referenced from the external module ( 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 (function() { $ (' body '). HTML (' It works! ' )});
Five. cooperate with Grunt/gulpWith Gulp as an example, we can mix and match:
gulp.task ("webpack", function (callback) { /span>// run Webpack webpack ({ // configuration }, function (err, stats) { if (err) throw new Gutil. Pluginerror ("webpack" [webpack] " // output options })); Callback (); });});
of course, We just need to write the configuration to Webpack ({...}) to go, no need to write webpack.config.js.
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-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 ~
Installation and use of Webpack Primer--webpack