Getting Started Webpack (condensed learning Webpack)

Source: Internet
Author: User
Tags naming convention

cooked words Condensed is the essence, haha, so simple rough introduction, write down is the essence.

It's not the first time I've heard of Webpack, but my start is a little late and now I see it. Straight to the point ~

1 1.什么是webpack?

Webpack is now the hottest front-end resource modular management and Packaging tool (a packager) that can package many loose modules into a front-end resource that fits into a production environment, and can also code-separate modules that need to be loaded, and then asynchronously load them when they actually need them. With loader conversion, any resource can be seen as a module, such as COMMONJS module, AMD module, JS CSS, JSON, etc., it will be based on the module's dependency on the static analysis, and then the module according to the specified rules to generate the corresponding static resources.

1 2.为什么要有webpack等打包器?

Normal module loading method is introduced in the <script> tag, this situation is under the Global Action Mode window, the disadvantage is that it can only be loaded in the writing order of <script>, and the global scope is prone to conflict, It is difficult to manage with the introduction of a larger number of files.

Furthermore, if each module is requested to cause too many requests, which causes the application to start slowly, however, compressing all the files into a single file, loading all the modules in a single request can result in a waste of traffic and a slow initialization process.

So when compiling the static analysis of all the code, analyze the types and dependencies of each module, and then submit them to the appropriate loader processing, so webpack came into being.

1 3.COMMONJS模块,AMD模块,CMD模块,UMD模块几种常用模块?

COMMONJS: Allows the module to synchronously load other patterns required by the Require method, and then exports the interfaces that need to be exposed through exports or module.exports.

Eg:require ("module");       Require ("./script.js");       Export.dostuff=function () {};       Module.exports=somevalue;

Pros: Each module can be reused, and NPM already has a lot of packages available for use.

Disadvantage: Only synchronous loading, synchronization means blocking loading, so not suitable in the browser environment, because the browser's resources are synchronous loading, can not be non-blocking parallel loading of multiple modules.

Application Example: Nodejs

AMD module: It specifies all dependent dependencies when declaring the module, and also as a formal parameter to the factory, which is pre-dependent for the dependent module.

Eg:  define ("module", ["Dep1", "DEP2"], function (d1, D2) {return someexportedvalue;});   Require (["module", ".. /file "],   function (module, file) {/* ... */});

advantages: suitable for loading modules asynchronously, in a browser environment, and can run multiple modules in parallel. The opposite of Commonjs.

Cons: Add all the dependencies in advance and the code is much more complex.

Application example: Requirejs,curl

CMD module: Similar to AMD, and has great compatibility with COMMONJS.

Eg:define (function (Require, exports, module) {  var $ = require (' jquery ');  var Spinning = require ('./spinning ');  exports.dosomething = ... module.exports = ...})

Pros: Easy to run your code in Nodejs

Cons: Dependent on SPM packaging, module load logic comparison heavy,

Application Example: Sea.js

UMD module: The main solution to the cross-platform problem of module definition

Eg:  import "jquery";   Export function Dostuff () {}   module "Localmodule" {}

Pros: Easy static Analysis , the future-oriented ES standard;

cons: Native browsers are not supported.

1 4. How do I use Webpack?

pretend that you have node. js installed in your computer and enter: NPM install webpack-g , you can view the installation information through WEBPACK-H.

(1). Pretend to create a project test, go to the project path, create a index.html page, code such as:

(2) Then create a file named: Bundle.js and introduce it in the index.html. There is no code in this file that needs to be written.

(3) in creating a file named Entry.js, do not need to be introduced in the Index.html page yo, this file is used to write content.

/**entry.js**/document.write ("Hello World");

(4) The entry.js is then packaged into the Bundle.js file, Webpack parses the portal file, parses the individual files that contain the dependencies, and then packs them into the bundle.js

Webpack Entry.js Bundle.js

Webpack Packaging is the principle of assigning each module a unique ID and through this ID index and Access module, start, will execute the code inside the Entry.js, the other modules will be executed when running require.

(5) When you open the Bundle.js file view, you can see that there is already code in it:

(6) Run the inde.html page and you will see Hello World in the browser.

But Webpack itself is only able to handle JavaScript modules, if you encounter Css,json and other module files, you need to use loader conversion. Loader is a changer, a tool that can input any resource but will eventually help you turn it into a JS module.

In general loader has the following points:

1. Pipeline mode chain call (allow multiple file conversion, the final output JS file). 2.loader can be executed synchronously or asynchronously 3. If in Nodejs environment, can do anything 4.loader load can accept the parameter.

5. You can bind different types of files by file name extension. 6.loader is released and installed via NPM. 7. By defining Package.json, you can also export a loader to use, the naming convention is: Xxx-loader. What is usually named after what function.

Here's a straight try:

123456789 (1)在项目里面在新建一个名为:style.css的文件:输入 body{ background:green}(2)修改entry.js  加入这一句  require("!style-loader!css-loader!./style.css") (3)安装Loader.  npm install css-loader style-loader     先用css-loader读取它,再用style-loader将它插入页面中。 (4)重新打包:webpack entry.js bundle.js(5)刷新index.html页面可以看到效果。

If there is an error, CMD is packaged and displayed, and Fireug is displayed when the index.html is run.

The loader converter can also be executed through a configuration file.

(1) Complete by adding a new configuration to the Package.json. Dedependencies

(2) in the new configuration of the Webpack.config.js file

var webpack = require (' webpack ') Module.exports = {    resolve: {fallback:path.join (__dirname, "Node_modules")},    Resolveloader: {fallback:path.join (__dirname, "Node_modules")},    entry: './entry.js ',    output: {        path: __ DirName,        filename: ' Bundle.js '    },    module: {        loaders: [            {test:/\.css$/, Loader: ' Style!css '}        ]    },    plugins:[        new Webpack. Bannerplugin (' This file was created by Yu ')    ]}

(3) Run Webpack directly, refresh index.html to see the effect

Getting Started Webpack (condensed learning 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.