hot load那点事 (2)

可以看到这里有两种handler,NodeFsHandler和FsEventsHandler。 还没没有得到是咋监听的,那么继续go on, 先看看NodeFsHandler._addToNodeFs。
打开chokidar/lib/nodefs-handler.js
_addToNodeFs ==> _handleFile ==> _watchWithNodeFs ==> setFsWatchListener ==> createFsWatchInstance

var fs = require('fs'); ...... function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { var handleEvent = function(rawEvent, evPath) { listener(path); emitRaw(rawEvent, evPath, {watchedPath: path}); // emit based on events occurring for files from a directory's watcher in // case the file's watcher misses it (and rely on throttling to de-dupe) if (evPath && path !== evPath) { fsWatchBroadcast( sysPath.resolve(path, evPath), 'listeners', sysPath.join(path, evPath) ); } }; try { return fs.watch(path, options, handleEvent); } catch (error) { errHandler(error); } }

调用的就是fs模块的。
呵呵,感觉自己读书少,还是得多看文档。

我们再看看FsEventsHandler
_addToFsEvents ==>_watchWithFsEvents==> createFSEventsInstance==>setFSEventsListener

try { fsevents = require('fsevents'); } catch (error) { if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error) } // Returns new fsevents instance function createFSEventsInstance(path, callback) { return (new fsevents(path)).on('fsevent', callback).start(); }

那我们再接着看看fsevents

/* jshint node:true */ 'use strict'; if (process.platform !== 'darwin') { throw new Error(`Module 'fsevents' is not compatible with platform '${process.platform}'`); } const { stat } = require('fs'); const Native = require('./fsevents.node'); const { EventEmitter } = require('events'); const native = new WeakMap(); class FSEvents { constructor(path, handler) { if ('string' !== typeof path) throw new TypeError('path must be a string'); if ('function' !== typeof handler) throw new TypeError('function must be a function'); Object.defineProperties(this, { path: { value: path }, handler: { value: handler } }); } start() { if (native.has(this)) return; const instance = Native.start(this.path, this.handler); native.set(this, instance); return this; }

平台只支持darwin,这是嘛呢,我问node开发,告诉我大致是Mac OS吧,那我就相信吧。

require('./fsevents.node') 引用的是c++扩展

Native.start(this.path, this.handler) 就是监听,哦哦,原来是这样。

最后我们打开 webpack-dev-server 的/lib/Server.js 文件。

const watcher = chokidar.watch(watchPath, options); watcher.on('change', () => { this.sockWrite(this.sockets, 'content-changed'); });

也是这个chokidar, 那么我感觉我能做好多事情了。
亲,你做一个修改后直接发布的应用吧,好歹,好歹。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpsxfj.html