浅析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模块做了以一些处置惩罚,文件的输入,输出,缓存,监听…

    原文作者:织雪纱奈
    原文地址: https://segmentfault.com/a/1190000017952254
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞