浅析webpack源码之NodeEnvironmentPlugin模块总览(六)

本文深入探讨Webpack构建过程,解析NodeEnvironmentPlugin如何通过重新封装Node.js的fs模块来处理文件输入、输出、缓存及监听,优化编译流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

进入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模块做了以一些处理,文件的输入,输出,缓存,监听...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值