Webpack模塊打包器
Webpack 是一個(gè)模塊打包器,主要目的是在瀏覽器上打包 JavaScript 文件。
TL;DR
- 捆綁 ES 模塊、CommonJS 和 AMD 模塊(以及綁定)。
- 可以創(chuàng)建在運(yùn)行時(shí)異步加載的單個(gè)捆綁包或多個(gè)塊(以減少初始加載時(shí)間)。
- 在編譯過程中解決了依賴性,從而減小了運(yùn)行時(shí)大小。
- 加載程序可以在編譯時(shí)對(duì)文件進(jìn)行預(yù)處理,例如,將 TypeScript 轉(zhuǎn)換為 JavaScript、將Handlebars字符串轉(zhuǎn)換為已編譯函數(shù)、將圖像轉(zhuǎn)換為 Base64,等等。
- 高度模塊化的插件系統(tǒng)可以執(zhí)行您的應(yīng)用程序所需的其他任何操作。
原理
示例代碼
// webpack is a module bundler
// This means webpack takes modules with dependencies
// and emits static assets representing those modules.
// dependencies can be written in CommonJs
var commonjs = require("./commonjs");
// or in AMD
define(["amd-module", "../file"], function(amdModule, file) {
// while previous constructs are sync
// this is async
require(["big-module/big/file"], function(big) {
// for async dependencies webpack splits
// your application into multiple "chunks".
// This part of your application is
// loaded on demand (Code Splitting)
var stuff = require("../my/stuff");
// "../my/stuff" is also loaded on demand
// because it's in the callback function
// of the AMD require
});
});
require("coffee!./cup.coffee");
// "Loaders" can be used to preprocess files.
// They can be prefixed in the require call
// or configured in the configuration.
require("./cup");
// This does the same when you add ".coffee" to the extensions
// and configure the "coffee" loader for /\.coffee$/
function loadTemplate(name) {
return require("./templates/" + name + ".jade");
// many expressions are supported in require calls
// a clever parser extracts information and concludes
// that everything in "./templates" that matches
// /\.jade$/ should be included in the bundle, as it
// can be required.
}
// ... and you can combine everything
function loadTemplateAsync(name, callback) {
require(["bundle?lazy!./templates/" + name + ".jade"],
function(templateBundle) {
templateBundle(callback);
});
}評(píng)論
圖片
表情
