honkit
Version:
HonKit is building beautiful books using Markdown.
52 lines (51 loc) • 2.11 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const chokidar_1 = __importDefault(require("chokidar"));
const parsers_1 = __importDefault(require("../parsers"));
/**
* Watch a folder and call callback when a file is modified
*
* @param {WatchOptions} options
* @return {FSWatcher} The chokidar watcher instance
*/
function watch(options) {
const { callback, outputFolder } = options;
const dir = path_1.default.resolve(options.watchDir);
const toWatch = ["book.json", "book.js", "_layouts/**"];
// Watch all parsable files
parsers_1.default.extensions.forEach((ext) => {
toWatch.push(`**/*${ext}`);
});
// Build ignored patterns
// Always ignore _book and node_modules
// https://github.com/honkit/honkit/issues/269
const ignored = ["_book/**", "node_modules/**"];
// If a custom output folder is specified, ignore it too
// This prevents infinite rebuild loops when output folder is inside the watched directory
// https://github.com/honkit/honkit/issues/491
if (outputFolder) {
// Convert to forward slashes for glob pattern (Windows compatibility)
const outputRelative = path_1.default.relative(dir, path_1.default.resolve(dir, outputFolder)).replace(/\\/g, "/");
// Only add to ignored if the output folder is inside the watched directory
if (outputRelative && !outputRelative.startsWith("..") && !path_1.default.isAbsolute(outputRelative)) {
ignored.push(`${outputRelative}/**`);
}
}
const watcher = chokidar_1.default.watch(toWatch, {
cwd: dir,
ignored: ignored,
ignoreInitial: true
});
watcher.on("all", (eventType, filepath) => {
callback(null, path_1.default.resolve(dir, filepath), eventType);
});
watcher.on("error", (err) => {
callback(err);
});
return watcher;
}
exports.default = watch;