Webpack: module manager for Web development [go]

Source: Internet
Author: User

Webpack: module manager for Web development

Original address: http://hanjianwei.com/2014/09/10/webpack-package-manager-for-web/

2014 SEP

For developers, a good package manager can make work more effective. Most of the popular programming languages now have their own package management systems. In recent years, web development has become more and more popular, and its development tools have become more and more useful, and Webpack is a package manager designed for Web development. It is well managed, packaged with HTML, Javascript, CSS, and various static files (pictures, fonts, etc.) used in web development, making the development process more efficient.

Modular programming

For a long time, web developers have put the required JavaScript, CSS files into HTML, which is cumbersome to manage for large projects. The advent of node. JS changed this state, and although the JavaScript module was not a node. js invention, it was true that it carried the concept forward.

But node. js, after all, is for the service side, in order to use the modular technology browser, people have created a lot of tools: Requirejs, Browserify, Labjs, Sea.js, Duo and so on. At the same time, because the JavaScript standard does not define the module specification, people define a series of different module definitions: CommonJS, AMD, CMD, UMD and so on. It is really a sad thing to hope that the advent of the ES6 module will stop the state of this division.

Webpack supports both COMMONJS and AMD modules, and supports shimming modules for unsupported module formats. To give a simple example:

// content.jsmodule.exports = "It works from content.js.";
// entry.jsdocument.write(require("./content.js"));
<!-- index.html --><meta charset="utf-8"> <body> <script type="text/javascript" src="bundle.js" charset="utf-8"></script> </body>

Here entry.js is the portal file, which is loaded content.js . To compile from a command-line pair entry.js :

$ webpack ./entry.js bundle.js

Open index.html and you will see content.js that the content is already loaded in.

Web development uses not only JavaScript, but also CSS and a variety of static files. Webpack defines something called the loader loader, which can convert various resource files and load them into the browser in the correct format. For example, if we have a corresponding CSS file for the above program:

/* style.css */body {  background: yellow;}

Let's modify entry.js it to load the CSS:

require("!style!css!./style.css");document.write(require("./content.js"));

Then recompile and open index.html it to see the CSS loaded in. We must install the required loader before executing the above procedure:

npm install --save-dev style-loader css-loader

At compile time, Css-loader reads the CSS file, processes the import in it, returns the CSS code, and Style-loader returns the CSS code as the DOM's style. If you are using SASS, just change the Require statement to the require("!style!css!sass!./style.scss") right one.

Webpack provides a number of common loader that can be used to require in the development of files, creating a single JavaScript that is easy to publish.

The above require CSS code, although powerful, but it is cumbersome to write, Webpack support in the configuration file configuration, matching the conditions of the file with the same set of loader for processing. Here is a set of loader I use:

{Module:{Loaders:[{Test:/\.coffee$/,Loader:' Coffee '},{Test:/\.html$/,Loader:' HTML '},{Test:/\.json$/,Loader:' JSON '},{Test:/\.css$/,Loader:' Style!css!autoprefixer '},{Test:/\.scss$/,Loader:' Style!css!autoprefixer!sass '},{Test:/\.woff$/loader:  "url?limit=10000&minetype= Application/font-woff "}, {test: /\.ttf$/loader:  "file" {test: /\.eot$/ Span class= "NX" >loader:  "file" }, { test: /\.svg$/loader :  "file" } ] }}    

With the above configuration, the require(‘./style.css‘) system automatically executes the autoprefixer first, then loads the CSS and then loads the DOM's style.

In addition, Webpack supports plug-ins for various operations such as compressing and replacing JavaScript.

Management of dependent modules

Webpack does not provide a module download, but it can work well with the existing Package manager. You can use NPM, Bower, component, and so on to manage your web development resources while loading them in Webpack.

Webpack file loading is divided into three types:

    • Absolute path, for example require(‘/home/me/file‘) . This will first check if the target is a directory, and if it is a directory check package.json the main field (you can have webpack check the Bower field at the same time), or if there is no package.json main field, it will be used index as the file name. After the above procedure, we resolve to an absolute path of the file name, and then try to add the extension (the extension can be webpack.config.js set in), the first existing file as the final result.
    • Relative paths, such as require(‘./file‘) . Use the current path or directory as a relative path in the configuration file context . The loading process is similar to the absolute path.
    • The module path, such as require(‘module/lib/file‘) . is found in all the lookup directories in the configuration file.

For complex module paths, you can also set aliases. An example of a path resolution configuration:

{Resolve:{Root:[AppRoot,Noderoot,Bowerroot], modulesdirectories: [appmoduleroot], alias: { ' angular ': ' Angular/angular ', ' Lodash ': ' Lodash/dist/lodash ' }, extensions: [' ' , '. js ', '. Coffee ', '. html ', '. css ','. scss ' }}  
Integration of tools

Webpack can be well integrated with grunt, gulp, karma and other existing tools.

In addition to outputting a single file, Webpack also supports code splitting, multi-entry, and runtime module substitution, a tool that is well worth the attention of web developers.

Finally, attach my configuration file:

Webpack.config.jsVarPath=Require(' Path ');VarWebpack=Require(' Webpack ');VarAppRoot=Path.Join(__dirname,' App ');VarAppmoduleroot=Path.Join(__dirname,' App/components ');VarBowerroot=Path.Join(__dirname,' Bower_components ');VarNoderoot=Path.Join(__dirname,' Node_modules ');Module.Exports={Entry:' App ',Output:{Path:Path.Resolve('./app/assets '),FileName:' Bundle.js ',Publicpath:'/assets/'},Resolve:{Root:[AppRoot,Noderoot,Bowerroot],Modulesdirectories:[Appmoduleroot],Alias:{' Angular-ui-tree ':' angular-ui-tree/dist/',' Angular-date-range-picker ':' Angular-date-range-picker/build/'},Extensions:[‘‘,'. js ','. Coffee ','. html ','. css ','. Scss ']},Resolveloader:{Root:Noderoot},Plugins:[NewWebpack.Provideplugin({_:' Lodash '}),NewWebpack.Resolverplugin([NewWebpack.Resolverplugin.Directorydescriptionfileplugin("Bower.json",["Main"])])],Module:{Loaders:[{Test:/\.coffee$/,Loader:' Coffee '},{Test:/\.html$/,Loader:' HTML '},{Test:/\.json$/,Loader:' JSON '},{Test:/\.css$/,Loader:' Style!css!autoprefixer '},{Test:/\.scss$/,Loader:' Style!css!autoprefixer!sass '},{Test:/\.woff$/loader:  "url?limit=10000&minetype= Application/font-woff "}, {test: /\.ttf$/loader:  "file" {test: /\.eot$/ Span class= "NX" >loader:  "file" }, { test: /\.svg$/loader :  "file" } ] }};    

Webpack: module manager for Web development [go]

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.