Node.js API
webpack提供了同Node.js運(yùn)行時(shí)通訊的Node.js API。
Node.js API在需要自定義開(kāi)發(fā)或構(gòu)建流程的場(chǎng)景中很有用。
因?yàn)樗械娜罩据敵黾板e(cuò)誤處理都必須人工處理,沒(méi)辦法自動(dòng)處理。
webpack只負(fù)責(zé)編譯功能。因?yàn)檫@個(gè)原因stats配置在webpack()調(diào)用中不起任何作用。
Installation
如果想使用Node.js API,需要首先安裝webpack。
npm install webpack --save-dev
在Node.js代碼中引入webpack 模塊。
const webpack = require("webpack");
// Or if you prefer ES2015:
import webpack from "webpack";
webpack()
導(dǎo)入的webpack方法可以傳遞Configuration Object并在提供回調(diào)函數(shù)的情況下運(yùn)行webapck compiler。
const webpack = require("webpack");
webpack({
// Configuration Object
}, (err, stats) => {
if (err || stats.hasErrors()) {
// Handle errors here
}
// Done processing
});
err對(duì)象不包含編譯錯(cuò)誤的相關(guān)信息,編譯的錯(cuò)誤信息需要單獨(dú)通過(guò)
stats.hasErrors()來(lái)獲取.err對(duì)象只包含webpack相關(guān)的錯(cuò)誤問(wèn)題,比如缺少某項(xiàng)配置。
Note可以給webpack function傳遞一個(gè)配置數(shù)組:
webpack([
{ /* Configuration Object */ },
{ /* Configuration Object */ },
{ /* Configuration Object */ }
], (err, stats) => {
// ...
});
當(dāng)有多個(gè)配置文件時(shí)webpack默認(rèn)是串行處理的,只有在前一個(gè)處理完成后,才會(huì)處理后一個(gè)。
如果希望webpack并行處理配置項(xiàng),可以使用parallel-webpack
Compiler Instance
如果不想webpack function中傳遞回調(diào)callback。
webpack function會(huì)返回Compiler對(duì)象。
該Compiler實(shí)例可以用來(lái)觸發(fā)webpack 運(yùn)行或構(gòu)建并監(jiān)控文件改變。
比較像CLIApi。
Compiler實(shí)例提供以下方法
- .run(callback)
- .watch(watchOptions, handler)
Run
調(diào)用Compiler的run方法,類似上面運(yùn)行的運(yùn)行webpack的方法。
const webpack = require("webpack");
const compiler = webpack({
// Configuration Object
});
compiler.run((err, stats) => {
// ...
});
Watching
調(diào)用watch方法,觸發(fā)webpack runner。并會(huì)監(jiān)控文件的改變(類似CLI: webpack --watch).
在webpack監(jiān)控到改變之后,會(huì)重新運(yùn)行。
該函數(shù)會(huì)返回一個(gè)Watching對(duì)象。
//函數(shù)聲明
//watch(watchOptions,callback)
const webpack = require("webpack");
const compiler = webpack({
// Configuration Object
});
const watching = compiler.watch({
/* watchOptions */
}, (err, stats) => {
// Print watch/build result here...
console.log(stats);
});
Watching的配置項(xiàng)詳情參見(jiàn)配置項(xiàng)詳情
Close Watching
watch方法返回的Watching對(duì)象提供了.close(callback)方法。
調(diào)用該方法會(huì)終止對(duì)文件的監(jiān)控
watching.close(() => {
console.log("Watching Ended.");
});
已關(guān)閉的或被設(shè)位invalidated的watcher不容許再次被運(yùn)行
Invalidate Watching
手動(dòng)指定本次編譯被廢棄,但仍然對(duì)文件進(jìn)行監(jiān)控。
watching.invalidate(() => {
console.warn("Invalidated.");
});
Stats Object
stats對(duì)象是webpack回調(diào)函數(shù)的第二個(gè)參數(shù)。
主要用來(lái)顯示代碼編譯過(guò)程中的相關(guān)信息,主要包括
- Errors and Warnings(if any)
- Timings
- Module and Chunk Information
- etc.
webpack CLI使用這些信息,
將格式化后的日志打印到console中。
該對(duì)象對(duì)外提供下面這些方法。
stats.hasErrors
用來(lái)檢測(cè)編譯期是否有error產(chǎn)生,返回true或false.
stats.hasWarnings
用來(lái)檢測(cè)編譯期是否有warning產(chǎn)生,返回true或false.
stats.toJson
將編譯信息作為JSON object返回。options可以是string或object。
使用object可以進(jìn)行細(xì)粒度的配置。
//string
stats.toJson("minimal"); // more options: "verbose", etc.
//object
stats.toJson({
assets: false,
hash: true
});
可用的配置項(xiàng),參見(jiàn)dev_server中關(guān)于stats的配置。
使用該配置打印的日志示例
stats.toString(options)
返回格式化后的編譯信息(類似CLI 中的輸出)。
配置參數(shù)同stats.toJson(options)一致,除了添加了一個(gè)額外的配置
stats.toString({
// ...
// Add console colors
colors: true
});
下面為stats.toString的使用示例
const webpack = require("webpack");
webpack({
// Configuration Object
}, (err, stats) => {
if (err) {
console.error(err);
return;
}
console.log(stats.toString({
chunks: false, // Makes the build much quieter
colors: true // Shows colors in the console
}));
});
Error Handling
為了比較好的處理error,一般需要統(tǒng)計(jì)三種類型的error。
- 嚴(yán)重的webpack錯(cuò)誤(錯(cuò)誤的webpack配置 .etc)
- 編譯錯(cuò)誤(缺modules,語(yǔ)法錯(cuò)誤 .etc)
- 編譯警告
示例:
const webpack = require("webpack");
webpack({
// Configuration Object
}, (err, stats) => {
//處理webpack本身的error
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
//處理代碼編譯中產(chǎn)生的error
if (stats.hasErrors()) {
console.error(info.errors);
}
//處理代碼編譯中產(chǎn)生的warning
if (stats.hasWarnings()) {
console.warn(info.warnings)
}
// Log result...
});
Compiling to Memory
webpack將輸出文件寫(xiě)到指定的磁盤(pán)文件中,如果希望改變輸出文件的位置,
比如輸出到內(nèi)存,webDAV等,可以通過(guò)對(duì)Compiler的outputFileSystem配置進(jìn)行設(shè)置。
const MemoryFS = require("memory-fs");
const webpack = require("webpack");
const fs = new MemoryFS();
const compiler = webpack({ /* options*/ });
compiler.outputFileSystem = fs;
compiler.run((err, stats) => {
// Read the output later:
const content = fs.readFileSync("...");
});
輸出的文件系統(tǒng)需要兼容Node fs模塊接口