First you can look at the official documents, the documentation is the best teacher. Here also has a foreign friend to write the introductory introduction.
Webpack is an open source front-end module build tool developed by Tobias Koppers. Its basic function is to package multiple JavaScript files in a modular format into a single file, supporting both COMMONJS and AMD formats. But what makes it unique is that it provides a powerful loader API to define preprocessing logic for different file formats, allowing us to use CSS, templates, and even custom file formats as JavaScript modules. Webpack based on loader can also achieve a large number of advanced features, such as automatic block packaging and on-demand loading, image resource reference automatic positioning, depending on the size of the image to determine whether to use the Base64 inline, the development of the module hot replacement, etc., can be said to be one of the most competitive solutions in front-end construction field.
Why use Webpack
- He is similar to browserify but can separate your application into many files, and if you have many pages in your single page application, the user simply needs to download the code needed for the current page. If you jump to another page, they don't need to reload the generic code.
- He can replace grunt or gulp most of the functionality because he can build and package CSS, pre-process CSS, compile JS and pack pictures, and even more things.
- He supports AMD and COMMONJS as well as other modular systems (ANGULAR,ES6). If you don't know what to use, then you can use COMMONJS.
How to install the Webpack installation node. js
First you need to install Node.js,node with the Package management tool npm
.
Installing Webpack
Use npm install webpack -g
, the Webpack is installed globally in the local environment, you can use webpack
the command.
Using Webpack in your project
- By
npm init
instantiating the Package.json file.
- by
npm install webpack --save-dev
installing webpack
to a package.json
file.
- or by
npm install [email protected] --save-dev
installing the specified version webpack
into the package.json
file.
npm install webpack-dev-server --save-dev
Run the dev tools
webpack service locally by installing to a package.json
file.
How to use Webpack
1, webpack
after installation, you can use webpack
this command-line tool. Main command: webpack <entry> <output>
. You can switch to a directory that contains webpack.config.js to run the command:
webpack
Perform a development-time compilation
webpack -p
Perform compilation (compression) of the build environment once
webpack --watch
Continuous monitoring of incremental compilation at development time (soon)
webpack -d
Let him build sourcemaps.
webpack --progress
Show compilation Progress
webpack --colors
Display the color of a static resource
webpack --sort-modules-by, --sort-chunks-by, --sort-assets-by
Sort Modules/chunks/assets in a list
webpack --display-chunks
Show the compiled tiles
webpack --display-reasons
Show more Reference module reasons
webapck --display-error-details
Show more error messages
2, each project must be configured with one webpack.config.js
, it functions as normal gulpfile.js/Gruntfile.js
, is a configuration item, tell Webpack what it needs to do.
Let's look at a simple example:
var webpack = require (' Webpack '); module.exports = {Plug-in itemsPlugins: [Mention common JS to common.js fileNew Webpack.optimize.CommonsChunkPlugin (' Common.js '),Uniformly publish styles to Style.cssNew Extracttextplugin ("Style.css", {Allchunks:TrueDisableFalse}),Use Provideplugin to load modules with high frequencyNew Webpack. Provideplugin ({$:"Webpack-zepto"})],Page Portal File ConfigurationEntry: {Index:'./src/main.js '},Ingress file Output ConfigurationOutput: {Path: __dirname +'/dist/',FileName' [Name].js '},Module: {Loader configurationLoaders: [{Test/\.css$/, loader: ' style-loader! Css-loader '}, {test: /\.scss$/, Loader: ' Style!css!sass?sourcemap '}, {test: /\. (png|jpg) $/, loader: ' url-loader?limit=8192 '}]}, //Other solution configuration resolve: { extensions: [", '. Json ', . Scss '], alias: { Filter:path.join (__dirname, ' Src/filters ')}}};
Entry
entry
is the page portal file configuration, which can be a file or multiple entry files, which can be either an object format or an array format.
entry: { index : ‘./src/main.js‘} entry:[‘./src/main.js‘,‘./src/index.js‘]
Output
output
is the corresponding output item configuration, mainly including path
, filename
and publishPath
attributes. path
represents the output path, which filename
represents the output file name, which publishPath
represents the prefix address after a static resource is published.
Module.loaders
Module.loaders is the most critical piece of configuration. It tells Webpack that each type of file needs to be handled with what loader. Click here to view loader list.
module: {//loader configuration loaders: [//.css file using Style-loader and Css-loader to process {test: /\.css$/, loader: ' Style-loader!css-loader '}, //.scss file using Style-loader, Css-loader and Sass-loader to compile processing {test: /\.scss$/, loader: ' Style!css!sass?sourcemap '}, //picture file use Url-loader to process, less than 8kb directly to base64 {test: /\. ( png|jpg) $/, loader: ' url-loader?limit=8192 '}]}
There are 3 main ways to use loader:
1, in the page reference resource use
Require ("url-loader?mimetype=image/png!. /file.png ");
2. Use in the Webpack.config.js folder
{test:/.png$/, Loader: "Url?mimetype=image/png"};
3. Compile on the command line using the
Webpack--module-bind "Png=url-loader?mimetype=image/png";
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 also use File-loader to load resource files.
Plugins
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. Click here to view plugins list.
plugins: [// Mention common JS to common.js file new webpack.optimize.CommonsChunkPlugin (//to publish the style uniformly to style.css new extracttextplugin ( Span class= "hljs-string" > "Style.css", { allchunks: true, disable: false}), // Use Provideplugin to load a module with high frequency new webpack. Provideplugin ({ $: "Webpack-zepto"})]
As above, it contains two kinds:
1, the first kind of webpack comes with some plugins: webpack.ProvidePlugin
, webpack.optimize.CommonsChunkPlugin
,
2, the other one is npm
installed through the package: ExtractTextPlugin
.
Resolve
Finally, the resolve configuration, this piece is very well understood, directly write comments:
resolve: { // require时省略的扩展名,如:require(‘module‘) 不需要module.js extension: [‘‘, ‘.js‘], //别名 alias: { filter: path.join(__dirname, ‘src/filters‘) }}
Using Webpack-dev-server
Webpack-dev-server is based on the node. JS Express service, which includes a Socket.io lightweight runtime environment.
' Use strict 'var webpack =Require' Webpack ');var webpackdevserver =Require' Webpack-dev-server ');var config =Require'./webpack.config ');Configure code Auto-compilation and hot-replace plug-ins Config.entry.unshift ( ' webpack-dev-server/client?http://localhost:9090 ', "Webpack /hot/dev-server "); Config.plugins.push (new webpack. Hotmodulereplacementplugin ()); //configured here: Request Http://localhost:9090/index.php,// Equivalent to a local node service proxy request to Http://testapi.uhouzz.com/index.phpvar proxy = [{path: "/index.php/* ", Target: " http://pc.uhouzz.com ", Host: "pc.uhouzz.com"}] //start service var app = new Webpackdevserver (Webpack (config), {publicPath:config.output.publicPath, Hot:true, Historyapifallback: true, Proxy:proxy}); App.listen (9090);
As above, the reference webpack
and webpack-dev-server
module, start the service through Webpackdevserver, HotModuleReplacementPlugin
automatically compiles the page automatically by the plugin startup code. This way, when you modify the HTML, JS, or style files, the page will automatically compile and refresh.
HTML page Use
Directly on the page to introduce Webpack final generated page scripts and style files can be.
<! DOCTYPE html><Htmllang="EN" ><Head><Metacharset="Utf-8" ><Title>webpack Test</Title><LinkRel="Stylesheet"href="/dist/style.css" ></Head><body> <div id="app" ></div> <script src="/ Dist/common.js "></script> <script src="/dist/build.js "></ script></body></html>
Summarize
Webpack based on the introduction of the tutorial is here, I hope this article can help you, you can also refer to the following projects for reference.
Vue-cnodejs, based on the vue.js rewrite of the Cnodejs WebApp, wherein the webpack is used for packaging processing.
Webpack Entry-Level tutorials