Webpack Tutorial OneDevelopment Tips Enable Source-map
Now the code is merged after the code, not conducive to troubleshooting and positioning, only need to add in config
... Devtool: ' Eval-source-map ', ...
In this way, you will use the Source-map form to display the location of your error code directly.
Configuring the Webpack-dev-server Agent
Since commonly used webpack do react a kind of spa, then a typical example is the front-end separation. The backend is a restful server, no matter what is written. Assuming that the native he is similar to http:/ localhost:5000/api/* Such requests, now add the configuration to allow the AJAX request can directly proxy past.
Devserver: { hot:true, inline:true, //actually very simple, as long as the configuration of this parameter can be a proxy: { '/api/* ': { target : ' http://localhost:5000 ', secure:false } } ,
Restart after the discovery of/api/* requests are agent to http //localhost:5000 Go ~
More ways to see official documents Webpack Dev Server Proxy
Using Preloaders and Postloaders
Perhaps you want to write code to check if your JS conforms to jshint specifications, then the Grand recommendation Preloaders and Postloaders, the previous section we have been very familiar with loaders, with it to deal with various types of files. Perloaders, as the name implies, is handled before loaders execution, and the Webpack processing order is perloaders-loaders-postloaders
Installing Jshint
NPM Install Jshint-loader--save-dev
Configuring in config file
Module: {... The same syntax as loaders, very simple perloaders: [ { test:/\.jsx?$/, Include:app_path, loader: ' Jshint-loader ' } ]}...//configuration jshint option, support ES6 checksum jshint: { "Esnext": true},
Okay, now every time npm run start, you can see the jshint message.
Load jquery plugin or other legacy third-party libraries
This is a very useful content!
Your project will sometimes load a variety of third-party libraries, some old libraries do not support advanced formats such as AMD or COMMONJS, such as some jquery plug-ins, they all rely on jquery, if the direct reference will be the error jquery is not Undefined this kind of error, there are several ways to solve
First create a jquery plugin:plugin.js
(function ($) { Const SHADE = "#556b2f"; $.fn.greenify = function () { this.css ("Color", shade); return this; };} (JQuery));
The first method uses Webpack. Provideplugin
Webpack provides a plug-in that inserts a global variable into all the code and configures it in Config.js
... Plugins: [ new Htmlwebpackplugin ({ title: ' Hello World App ' ), //provide $, jQuery and Window.jquery To every script new Webpack. Provideplugin ({ $: "jquery", jquery: "jquery", "window.jquery": "jquery" }) ] ...
Referencing in JS
...//This also does not need to be because $, jquery, window.jquery can be directly used//import $ from ' jquery '; Import './plugin.js ';.. mypromise.then (( Number) = { $ (' body '). Append (' <p>promise result is ' + number + ' Now ' + Moment (). Format () + ' </p> '); Call our jquery plugin! $ (' P '). greenify ();}); ...
found that the color we inserted in the P has become green!
The second method uses Imports-loader
Install this loader first
NPM Install Imports-loader--save-dev
And then in the portal JS
Note that this is the type of jquery that we inserted into the plugin.js directly inside the//equivalent to the beginning of the file added var JQuery = require (' jquery '); Import ' Imports?jquery=jquery !. /plugin.js ';//The following code is Mypromise.then ((number) + = { $ (' body '). Append (' <p>promise result is ' + number + ' now Is ' + Moment (). Format () + ' </p> '); Call our jquery plugin! $ (' P '). greenify ();});
deploy on-line
Just said the various situations are in the development time situation, then if the project has been developed, need to deploy on-line. We should create a separate config file, because we do not need some dev-tools,dev-server and jshint checksum when we deploy the Webpack on line.
Copy our existing config file, named Webpack.production.config.js, and delete the contents of the Devserver and other related developments.
Add a command to the Package.json.
"Scripts": { "start": "Webpack-dev-server--hot--inline", "Build": "Webpack--progress--profile--colors-- Config webpack.production.config.js " },
When it's time to go online, run
NPM Run Build
You can see that everything has been generated in the build folder.
Separating App.js and third-party libraries
Now we build only one bundle.js. If a third-party library is a lot, it will cause this file to be very large, slowing down the loading speed, now we have to divide the third-party library and the code of our app itself into two files.
Modify the entry entry file
Entry: { app:path.resolve (app_path, ' index.js '), //Add library vendors to be packaged in vendors : [' jquery ', ' moment '] },
Add Commonschunkplugin
Plugins: [// this uses UGLIFYJS to compress your JS code new Webpack.optimize.UglifyJsPlugin ({minimize:true}), // Package the array inside the portal file into Verdors.js new Webpack.optimize.CommonsChunkPlugin (' Vendors ', ' vendors.js '), new Htmlwebpackplugin ({ title: ' Hello World App ' ) ]
Add complete running NPM run build
The following structure is found in the build folder
Budle.jsindex.htmlvendors.js
Apps can't all be spas, can't just generate an HTML file, if you want to build multiple HTML pages so play? In fact, it is very simple: Now the demand is this, there are two pages, a call index.html It needs to refer to the two files of Vendors.js and App.js, as well as a mobile.html page where he will refer to the two files of Vendors.js and Mobile.js.
Start by creating a new portal file called Mobile.js, which is simpler than app.js
Import './main.scss '; import $ from ' jquery '; import ' imports?jquery=jquery!. /plugin.js '; $ (document). Ready (function () {Let app = document.createelement (' div '); app.innerhtml = '
Configure inside Config
Entry: { //Three entry files, app, mobile and vendors App:path.resolve (App_path, ' index.js '), mobile:path.resolve (app _path, ' mobile.js '), vendors: [' jquery ', ' moment '] }, output: { Path:build_path, //Note We have modified bundle.js to use an array [name] instead, he will generate multiple JS files according to the entry's portal file name, here is (App.js,mobile.js and vendors.js) filename: ' [name]. JS ' },
Originally we are no template files, the original use of the Htmlwebpackplugin default template. Who thought this great plugin can also customize the template. So create a dedicated template folder templates, add two template files in it index.html and mobile.html
Index.html
<! DOCTYPE html>
Mobile.html
<! DOCTYPE html>
Continue configuring Config.js, now let Htmlwebpackplugin can generate multiple files
//template folder path var Tem_path = Path.resolve (Root_path, ' templates ') ... plugins: [ ... Created two instances of Htmlwebpackplugin, generated two pages new Htmlwebpackplugin ({ title: ' Hello World app ', Template: Path.resolve (Tem_path, ' index.html '), filename: ' index.html ', //chunks This parameter tells the plugin which portals to refer to entry Chunks: [' app ', ' vendors '], //To insert script into the tag inject: ' Body ' }, new Htmlwebpackplugin ({ Title: ' Hello Mobile app ', template:path.resolve (Tem_path, ' mobile.html '), filename: ' mobile.html ', Chunks: [' mobile ', ' vendors '], inject: ' Body ' } ... ]
And then run
NPM Run Build
Look at the great files generated, no problem!
- App.js
- Mobile.js
- Vendors.js
- Index.html
- Mobile.html
Look at the reference correspondence, perfect!!
Index.html
<body>
Mobile.html
<body>
Generate a script of the hash name to prevent cachingClassic problem, the code is updated, but the browser has a cache, it will be silly. How to solve, change the name of Bai. You can add parameters directly to the back, or you can change the file name directly. Webpack provides us with a very simple way to file-based MD5, as long as the
Output: { Path:build_path, //As long as the hash is added to the parameter, filename: ' [name].[ Hash].js '},
After running the build, look at the resulting file, perfect ~
Index.html
<body>
Well, now that you understand Webpack as a module bundler, make a diagram of our example to help you understand.
ConclusionThe second part ends here, this section discusses the use of many webpack skills, it seems trivial, but in your work may be very practical, the next part will appear on the tall things we all look forward to, webpack and react and backbone and so on the combination.
Very hard LinksRepo code has been updated, want to see all the source can clone under the Vikingmute/webpack-basic-starter GitHub
Also this series of articles about Webpack can be found on GitHub vikingmute/webpack-for-fools GitHub
Zhang Xuan
Links: http://zhuanlan.zhihu.com/p/20397902
Source: Know
Webpack Tutorial II