Webpack learning notes, webpack

Source: Internet
Author: User

Webpack learning notes, webpack
What is

Webpack is a module packaging tool that uses dependency processing modules to generate static resources for those modules.

Observe that webpack regards all resources (js, css, and images) as modules -- css can be referenced in webpack, and image dataUrl can be embedded in css. for different types of resources, webpack has a module loader. The webpack module packer analyzes the dependencies between modules and generates optimized and merged static resources.

Why?

Today, websites are becoming a web application: a page contains more and more javascript code, and a large amount of code is found on the client. Code is divided into small modules through the module system, which is an effective way to manage a large number of codes. There are currently several ways to implement the definition of modules and dependencies:

  • <script>Tag

    • Introduction: This is the most basic code modularization method. This module output method exposes a global object in the interface, that iswindowTo access the dependent module through a global object.
    • Instance:

      <script src="module1.js"></script><script src="module2.js"></script><script src="libraryA.js"></script><script src="module3.js"></script>
    • Disadvantages
      • Different modules are prone to conflicts.
      • The order of loading depends on the sequence of script tags
      • In a large project, the script tag list may become very long and difficult to manage
  • CommonJS

    • Introduction: CommonJS uses the synchronous require method to load the dependency module.exportsBind the property to the object ormodule.exportsAssign values to define output,
    • Instance:

      require("module");require("../file.js");exports.doStuff = function() {};module.exports = someValue;
    • Advantages
      • Can the server module be reused?
      • Many modules developed in this way (NPM)
      • Very simple and easy to use
    • Disadvantages
      • Blocking calls are not applicable to networks (network requests are asynchronous)
      • Multiple modules cannot be concurrently requested
    • Implementation
      • Node. js
      • Browserify
      • Modules-webmake
      • Wrep
  • AMD

    • Introduction: AMD is an asynchronous version of the module CommonJS
    • Instance:

      require(["module", "../file"], function(module, file) { /* ... */ });define("mymodule", ["dep1", "dep2"], function(d1, d2) {    return someExportedValue;});
    • Advantages
      • Asynchronous request Method
      • Load multiple modules in parallel
    • Disadvantages
      • It is hard to read and write code.
      • It looks like a work und
    • Implementation
      • Require. js
      • Curl
  • ES6

    • Introduction: EcmaScript6 adds some syntax to Javascript to form another module system.
    • Instance:

      import "jquery";export function doStuff() {}module "localModule" {}
    • Advantages
      • Static analysis is simple?
      • ES standard, not outdated

The module determines that to be executed on the client, it must be transmitted from the server to the client. There are two extreme transmission modes:

  • One request and one module
    • Advantage: only the request transmission module
    • Disadvantage: multiple modules require multiple requests, affecting performance and slow application startup
  • One request to all modules
    • Advantage: less request consumption
    • Disadvantage: unnecessary modules are also transmitted to the client.

The loading methods of the above two modules are extreme. We need a method that can transmit modules more flexibly. When compiling all modules, divide the entire system into multiple smaller modules. Each module set is not loaded at the beginning and is loaded only when necessary. Therefore, the initialization does not contain all the module code. The division of a module set depends on the developer. For example, the modules that the module depends on are treated as a module set. When you access a function of the system, the module set for loading this function in one request.

After discussing the definition and loading of modules, we found that we only mentioned the Javascript module system, and there are many other static resources to load in the previous section, such: style Sheets, images, fonts, and html templates. Can we use require like javascript to load specified static resources? For example:

require("./style.css");require("./style.less");require("./template.jade");require("./image.png");

For a large project, we will encounter the above problems-module division and static resources. Currently, the existing module packaging tools are no longer applicable. The author of webpack has tried to expand the existing module packaging tools, but it cannot achieve all the building objectives.
Webpack goals:

  • Divides all modules into sub-module sets and loads them only when necessary.
  • Ensures low loading time
  • Treat every static resource as a module
  • Ability to integrate third-party libraries as modules
  • Ability to customize each part of the module package
  • Applicable to large projects

Webpack features

  • Module division
    Webpack not only supports CommonJS-supports synchronous dependencies, but also supports AMD-supports asynchronous dependencies. It is also a module division point to form a new module set.
  • Loader
    Webpack can only load local Javascript. Different static resources can be loaded through a series of loaders.
  • Intelligent Compilation
  • Plug-in system
    Webpack has rich plug-in systems, and most of its internal features are based on plug-in systems.
Installation and usage

In addition to using webpack on the command line interface, you can also directly use webpack in code.

  • Command line interface
    • webpack --entry entry.js --output bundle.js
    • webpack --config webpack.config.js
    • webpack --config webpack.config.js -d: Development Mode
    • webpack --config webpack.config.js -w: Observation mode
    • webpack --config webpack.config.js -p: Generation mode
  • Node. js-api

    • Simple Example

      var webpack = require("webpack");// returns a Compiler instancewebpack({    // configuration}, function(err, stats) {    // ...});
    • Complex example

      var webpack = require("webpack");// returns a Compiler instancevar compiler = webpack({    // configuration});compiler.run(function(err, stats) {    // ...});// orcompiler.watch({ // watch options:    aggregateTimeout: 300, // wait so long for more changes    poll: true // use polling instead of native watchers    // pass a number to set the polling interval}, function(err, stats) {    // ...});

FAQs:

  • Webpack command--confgiWhat is the option?
    --configIt is used to specify a configuration file instead of the options in the command line to simplify the command. If you directly executewebpackWebpack will find the name in the current directorywebpack.config.js.
  • ...
Simple Example

This example showsHello World!The source code is as follows:

  • Index.html

  • Entry. js

    document.write(require("./content.js"));
  • Content. js

    module.exports = "Hello World.";

Module packaging and running:

In addition to specifying the module entry file and module package generation file in the webpack command option, you can createwebpack.config.jsThe specific configuration is as follows. After configuration, enterwebpack(The configuration file is searched by default.webpack.config.js) Orwebpack --config webpack.config.js.webpack ./entry.js bundle.js.

module.exports = {    entry: "./entry.js",    output: {        path: __dirname,        filename: "bundle.js"    }};

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.