UNPKG

@launchmenu/hmr

Version:
91 lines 3.59 kB
"use strict"; var __spreadArrays = (this && this.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.referencelessRequire = void 0; var chokidar_1 = __importDefault(require("chokidar")); var path_1 = __importDefault(require("path")); /** * Listens to changes for a module and triggers the callback when data changed * @param dir The directory to check for changes in (path should be absolute) * @param onChange The callback to perform when data is changed * @param options Extra options * @returns A chokidar watcher */ function hmr(dir, onChange, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.timeoutTime, timeoutTime = _c === void 0 ? 500 : _c, target = _b.target; var timeoutID; var changed = []; var watcher = chokidar_1["default"] .watch(dir, { persistent: true, cwd: dir, ignoreInitial: true, ignored: ["**/node_modules/**/*", "**/.git/**/*"] }) .on("all", function (type, path) { var fullPath = path_1["default"].join(dir, path); changed.push(fullPath); clearTimeout(timeoutID); timeoutID = setTimeout(function () { var changedFiles = __spreadArrays(changed); var affectedFiles = __spreadArrays(changed); var _loop_1 = function () { var path_2 = changed.pop(); if (require.cache[path_2]) { delete require.cache[path_2]; // Find any modules that used this module, and recursively remove those from the cache too Object.values(require.cache).forEach(function (_a) { var filename = _a.filename, children = _a.children; var usedModule = children.find(function (child) { return child.filename == path_2; }); if (usedModule) { changed.push(filename); affectedFiles.push(filename); } }); } }; // Invalid changed cache entries while (changed.length > 0) { _loop_1(); } // Inform listener about the update if (!target || !require.cache[target]) onChange(changedFiles, affectedFiles); }, timeoutTime); }); return { watcher: watcher, destroy: function (fully) { if (fully === void 0) { fully = true; } watcher.close(); if (fully) clearTimeout(timeoutID); } }; } exports["default"] = hmr; /** * Requires without storing child references, such that HMR doesn't think you're dependent on the module and you should be invalidated * @param path The path to be required * @returns The output of the require call */ function referencelessRequire(path) { try { var result = require(path); return result; } finally { module.children = []; } } exports.referencelessRequire = referencelessRequire; //# sourceMappingURL=index.js.map