淺析webpack原始碼之NodeEnvironmentPlugin模組總覽(六)
進入webpack.js
//傳入地址,new Compiler出來一個複雜物件 compiler = new Compiler(options.context); // 把options掛載到物件上 compiler.options = options; new NodeEnvironmentPlugin().apply(compiler);
compiler太複雜
我們先看NodeEnvironmentPlugin
const NodeWatchFileSystem = require("./NodeWatchFileSystem"); const NodeOutputFileSystem = require("./NodeOutputFileSystem"); const NodeJsInputFileSystem = require("enhanced-resolve/lib/NodeJsInputFileSystem"); const CachedInputFileSystem = require("enhanced-resolve/lib/CachedInputFileSystem"); class NodeEnvironmentPlugin { apply(compiler) { // 可以快取輸入的檔案系統 compiler.inputFileSystem = new CachedInputFileSystem( new NodeJsInputFileSystem(), 60000 ); // 輸入檔案系統 const inputFileSystem = compiler.inputFileSystem; // 輸出檔案系統,掛載到compiler物件 compiler.outputFileSystem = new NodeOutputFileSystem(); // 傳入輸入檔案,監視檔案系統,掛載到compiler物件 compiler.watchFileSystem = new NodeWatchFileSystem( compiler.inputFileSystem ); // 新增事件流before-run compiler.hooks.beforeRun.tap("NodeEnvironmentPlugin", compiler => { if (compiler.inputFileSystem === inputFileSystem) inputFileSystem.purge(); }); } } module.exports = NodeEnvironmentPlugin;
開啟外掛NodeJsInputFileSystem.js
"use strict"; const fs = require("graceful-fs"); class NodeJsInputFileSystem { //讀取目錄下檔案 readdir(path, callback) { fs.readdir(path, (err, files) => { callback(err, files && files.map(file => { // 對檔名進行NFC格式化 return file.normalize ? file.normalize("NFC") : file; })); }); } //非同步讀取目錄下檔案 readdirSync(path) { const files = fs.readdirSync(path); return files && files.map(file => { return file.normalize ? file.normalize("NFC") : file; }); } } const fsMethods = [ "stat", "statSync", "readFile", "readFileSync", "readlink", "readlinkSync" ]; // 同步fs方法 for(const key of fsMethods) { Object.defineProperty(NodeJsInputFileSystem.prototype, key, { configurable: true, writable: true, value: fs[key].bind(fs) }); } module.exports = NodeJsInputFileSystem;
graceful-fs就是對node 原生fs 做了一層封裝,顯得更優雅
總體看來NodeEnvironmentPlugin這個模組就是對檔案做了處理,又重新封裝了node.js 對fs模組做了以一些處理,檔案的輸入,輸出,快取,監聽...