### watch() Method Source: https://context7.com/webpack/watchpack/llms.txt Starts watching specified files, directories, and missing files for changes. ```APIDOC ## Method: watch(options) ### Description Starts tracking files and directories. Calling this method again updates the watch list without creating redundant watcher instances. ### Parameters #### Request Body - **files** (Array) - Optional - List of file paths to track for content and existence changes. - **directories** (Array) - Optional - List of directory paths to track recursively. - **missing** (Array) - Optional - List of paths expected to not exist, tracking their creation. - **startTime** (number) - Optional - Timestamp; only report changes occurring after this time. ### Request Example { "files": ["/src/index.js"], "directories": ["/src/components"], "missing": ["/src/config.local.js"], "startTime": 1705314645000 } ``` -------------------------------- ### Start Watching Files and Directories Source: https://github.com/webpack/watchpack/blob/main/README.md Initiate file system watching using the `watch` method. This method accepts iterables for files, directories, and missing items. Subsequent calls to `watch` will override previous settings. ```javascript // Watchpack.prototype.watch({ // files: Iterable, // directories: Iterable, // missing: Iterable, // startTime?: number // }) wp.watch({ files: listOfFiles, directories: listOfDirectories, missing: listOfNotExistingItems, startTime: Date.now() - 10000, }); // starts watching these files and directories // calling this again will override the files and directories // files: can be files or directories, for files: content and existence changes are tracked // for directories: only existence and timestamp changes are tracked // directories: only directories, directory content (and content of children, ...) and // existence changes are tracked. // assumed to exist, when directory is not found without further information a remove event is emitted // missing: can be files or directories, // only existence changes are tracked // expected to not exist, no remove event is emitted when not found initially // files and directories are assumed to exist, when they are not found without further information a remove event is emitted // missing is assumed to not exist and no remove event is emitted ``` -------------------------------- ### Start Watching Files and Directories Source: https://context7.com/webpack/watchpack/llms.txt Use the watch method to track files, directories, and missing files. Calling this method updates the watch list without creating redundant watchers. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); // Modern API using options object wp.watch({ // Files: content and existence changes tracked files: [ path.join(__dirname, "src/index.js"), path.join(__dirname, "src/utils.js"), ], // Directories: recursive content changes tracked directories: [ path.join(__dirname, "src/components"), path.join(__dirname, "src/styles"), ], // Missing: expected to not exist, track creation missing: [ path.join(__dirname, "src/config.local.js"), ], // Start time: only report changes after this timestamp startTime: Date.now() - 10000, }); // Legacy API (deprecated but still supported) // wp.watch(files, directories, startTime); console.log("Started watching files and directories"); ``` -------------------------------- ### Watchpack Methods Source: https://github.com/webpack/watchpack/blob/main/README.md Details the core methods for managing file watching, including starting, pausing, and closing the watcher, as well as retrieving aggregated changes. ```APIDOC ## Watchpack Methods ### Description Provides methods to control the watching process and retrieve information about detected changes. ### `watch(options)` Starts or updates the files and directories to watch. #### Parameters - **files** (Iterable) - Required - An iterable of file or directory paths to watch. - **directories** (Iterable) - Required - An iterable of directory paths to watch. - **missing** (Iterable) - Required - An iterable of file or directory paths that are expected to not exist. - **startTime** (number) - Optional - A timestamp to use as the starting point for detecting changes. ### `pause()` Stops emitting events but keeps watchers open. Events are aggregated and can be retrieved later. ### `close()` Stops emitting events and closes all watchers. ### `getAggregated()` Returns the current aggregated changes and removals, and clears them from the watcher's internal state. #### Returns - `{ changes: Set, removals: Set }` - An object containing sets of changed and removed file paths. ### Request Example ```javascript // Starting to watch wp.watch({ files: listOfFiles, directories: listOfDirectories, missing: listOfNotExistingItems, startTime: Date.now() - 10000 }); // Pausing the watcher wp.pause(); // Getting aggregated changes const { changes, removals } = wp.getAggregated(); // Closing the watcher wp.close(); ``` ``` -------------------------------- ### Integrate Watchpack into a Dev Server Source: https://context7.com/webpack/watchpack/llms.txt Use this pattern to create a development server that monitors file changes and triggers rebuilds. Configure aggregate timeout, polling, and ignore patterns. Ensure proper lifecycle management with start() and stop() methods. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const fs = require("fs"); class DevServer { constructor(projectRoot) { this.projectRoot = projectRoot; this.watchpack = null; this.buildCache = new Map(); this.isBuilding = false; } start() { this.watchpack = new Watchpack({ aggregateTimeout: 300, poll: process.env.WATCHPACK_POLLING || false, ignored: [ "**/node_modules", "**/.git", "**/dist", "**/*.test.js", ], }); this.watchpack.on("change", (file, mtime, type) => { console.log(`[${type}] ${path.relative(this.projectRoot, file)}`); }); this.watchpack.on("aggregated", async (changes, removals) => { if (this.isBuilding) { console.log("Build in progress, queuing changes..."); return; } await this.rebuild(changes, removals); }); // Initial watch this.watchpack.watch({ files: [ path.join(this.projectRoot, "package.json"), path.join(this.projectRoot, "config.js"), ], directories: [ path.join(this.projectRoot, "src"), path.join(this.projectRoot, "public"), ], missing: [ path.join(this.projectRoot, ".env.local"), ], startTime: Date.now(), }); console.log("Dev server started, watching for changes..."); } async rebuild(changes, removals) { this.isBuilding = true; const startTime = Date.now(); try { // Handle removals for (const removed of removals) { this.buildCache.delete(removed); console.log(`Removed from cache: ${path.basename(removed)}`); } // Get time info for cache validation const timeInfo = this.watchpack.getTimeInfoEntries(); // Incremental rebuild only changed files for (const changed of changes) { const entry = timeInfo.get(changed); const cached = this.buildCache.get(changed); if (!cached || (entry && entry.safeTime > cached.buildTime)) { await this.buildFile(changed); } } console.log(`Build completed in ${Date.now() - startTime}ms`); } catch (error) { console.error("Build failed:", error.message); } finally { this.isBuilding = false; } } async buildFile(filePath) { // Simulate file processing const content = fs.readFileSync(filePath, "utf-8"); const processed = content; // Transform content here this.buildCache.set(filePath, { content: processed, buildTime: Date.now(), }); console.log(`Built: ${path.basename(filePath)}`); } stop() { if (this.watchpack) { this.watchpack.close(); this.watchpack = null; console.log("Dev server stopped"); } } } // Usage const server = new DevServer(__dirname); server.start(); process.on("SIGINT", () => { server.stop(); process.exit(0); }); ``` -------------------------------- ### Get All Time Info Entries Source: https://github.com/webpack/watchpack/blob/main/README.md Retrieve a map of all known time info objects for files and directories using `getTimeInfoEntries`. This includes information from files that are not directly watched. ```javascript // Watchpack.prototype.getTimeInfoEntries() const fileTimes = wp.getTimeInfoEntries(); // returns a Map with all known time info objects for files and directories // similar to collectTimeInfoEntries but returns a single map with all entries ``` -------------------------------- ### Get Known Change Times (Deprecated) Source: https://github.com/webpack/watchpack/blob/main/README.md The deprecated `getTimes()` method returns an object containing known change times for files, including those not directly watched. Use `getTimeInfoEntries()` for current functionality. ```javascript // (deprecated) // Watchpack.prototype.getTimes() const fileTimesOld = wp.getTimes(); // returns an object with all known change times for files // this include timestamps from files not directly watched // key: absolute path, value: timestamp as number ``` -------------------------------- ### Watchpack Initialization Source: https://github.com/webpack/watchpack/blob/main/README.md Demonstrates how to initialize a new Watchpack instance with various configuration options. ```APIDOC ## Watchpack Initialization ### Description Initializes a new Watchpack instance with configurable options to control watching behavior. ### Constructor `new Watchpack(options)` ### Parameters #### Options - **aggregateTimeout** (number) - Optional - The time in milliseconds to wait after the last change before firing the 'aggregated' event. - **poll** (boolean | number) - Optional - Enables polling for file changes. If `true`, uses the default interval. If a number, specifies the polling interval in milliseconds. Defaults to `undefined`, preferring native watching methods. - **followSymlinks** (boolean) - Optional - Determines whether to follow symbolic links. `true` follows symlinks and watches real files; `false` (default) watches only the specified items. - **ignored** (string | string[] | RegExp | function) - Optional - Specifies files or directories to ignore. Can be a glob pattern, an array of glob patterns, a regular expression, or a function that returns `true` to ignore an entry. ### Request Example ```javascript const Watchpack = require("watchpack"); const wp = new Watchpack({ aggregateTimeout: 1000, poll: true, followSymlinks: true, ignored: "**/.git" }); ``` ``` -------------------------------- ### Initialize Watchpack Instance Source: https://context7.com/webpack/watchpack/llms.txt Create a new Watchpack instance with custom configuration options for aggregation, polling, and ignore patterns. ```javascript const Watchpack = require("watchpack"); // Basic instantiation with default options const wp = new Watchpack(); // Full configuration with all options const wpConfigured = new Watchpack({ // Time to wait after a change before firing "aggregated" event (ms) aggregateTimeout: 1000, // Enable polling mode (useful for network paths) // poll: true - use default interval // poll: 10000 - use 10 second interval poll: false, // Follow symlinks and watch both symlink and real file followSymlinks: false, // Ignore patterns - multiple formats supported: // String glob pattern ignored: "**/.git", // Array of glob patterns // ignored: ["**/.git", "**/node_modules"], // Regular expression // ignored: /node_modules/, // Custom function // ignored: (entry) => entry.includes("node_modules") }); console.log("Watchpack instance created with aggregateTimeout:", wpConfigured.aggregateTimeout); // Output: Watchpack instance created with aggregateTimeout: 1000 ``` -------------------------------- ### Initialize Watchpack with Options Source: https://github.com/webpack/watchpack/blob/main/README.md Instantiate Watchpack with options like aggregateTimeout, poll, and ignored patterns. Use polling for network paths or when native watching fails. Ignored patterns can be strings, arrays, regex, or functions. ```javascript const Watchpack = require("watchpack"); const wp = new Watchpack({ // options: aggregateTimeout: 1000, // fire "aggregated" event when after a change for 1000ms no additional change occurred // aggregated defaults to undefined, which doesn't fire an "aggregated" event poll: true, // poll: true - use polling with the default interval // poll: 10000 - use polling with an interval of 10s // poll defaults to undefined, which prefer native watching methods // Note: enable polling when watching on a network path // When WATCHPACK_POLLING environment variable is set it will override this option followSymlinks: true, // true: follows symlinks and watches symlinks and real files // (This makes sense when symlinks has not been resolved yet, comes with a performance hit) // false (default): watches only specified item they may be real files or symlinks // (This makes sense when symlinks has already been resolved) ignored: "**/.git", // ignored: "string" - a glob pattern for files or folders that should not be watched // ignored: ["string", "string"] - multiple glob patterns that should be ignored // ignored: /regexp/ - a regular expression for files or folders that should not be watched // ignored: (entry) => boolean - an arbitrary function which must return truthy to ignore an entry // For all cases expect the arbitrary function the path will have path separator normalized to '/'. // All subdirectories are ignored too }); ``` -------------------------------- ### Enable Symlink Following Source: https://context7.com/webpack/watchpack/llms.txt Set followSymlinks to true to watch both the symlink and the target file. This ensures changes are detected regardless of the access path. ```javascript const Watchpack = require("watchpack"); const path = require("path"); // Enable symlink following const wp = new Watchpack({ aggregateTimeout: 1000, followSymlinks: true, }); wp.on("change", (filePath, mtime, type) => { console.log("Change detected:", filePath); console.log("Type:", type); }); // Project structure: // /project/ // node_modules/ // my-package -> /dev/my-package (symlink) // src/ // index.js // With followSymlinks: true, changes to /dev/my-package/index.js // will be detected even though we're watching via the symlink wp.watch({ files: [], directories: [ path.join(__dirname, "node_modules/my-package"), path.join(__dirname, "src"), ], }); console.log("Watching with symlink resolution enabled"); ``` -------------------------------- ### Configure ignored file patterns Source: https://context7.com/webpack/watchpack/llms.txt Demonstrates various ways to exclude files and directories using strings, arrays, regex, or custom functions. Paths are normalized to forward slashes before matching. ```javascript const Watchpack = require("watchpack"); const path = require("path"); // String glob pattern - matches files/directories const wp1 = new Watchpack({ ignored: "**/.git", }); // Array of glob patterns const wp2 = new Watchpack({ ignored: [ "**/.git", "**/node_modules", "**/*.log", "**/dist/**", ], }); // Regular expression const wp3 = new Watchpack({ ignored: /node_modules|\.git|dist/, }); // Custom function for complex logic const wp4 = new Watchpack({ ignored: (filePath) => { // Ignore hidden files if (path.basename(filePath).startsWith(".")) return true; // Ignore specific directories if (filePath.includes("node_modules")) return true; if (filePath.includes("__tests__")) return true; // Ignore large binary files if (filePath.endsWith(".bin")) return true; return false; }, }); // Start watching with ignore patterns wp2.watch({ files: [], directories: [path.join(__dirname, "project")], }); console.log("Watching with ignore patterns active"); ``` -------------------------------- ### Watchpack Constructor Source: https://context7.com/webpack/watchpack/llms.txt Initializes a new Watchpack instance with configuration for aggregation, polling, symlink handling, and ignore patterns. ```APIDOC ## Constructor: new Watchpack(options) ### Description Creates a new Watchpack instance. The options object allows configuration of how the watcher behaves. ### Parameters #### Request Body - **aggregateTimeout** (number) - Optional - Time in ms to wait after a change before firing the 'aggregated' event. - **poll** (boolean|number) - Optional - Enable polling mode. If true, uses default interval; if a number, uses that value as the interval in ms. - **followSymlinks** (boolean) - Optional - Whether to follow symlinks and watch both the symlink and the real file. - **ignored** (string|Array|RegExp|Function) - Optional - Patterns to ignore. Supports glob strings, arrays of globs, regex, or a filter function. ### Request Example { "aggregateTimeout": 1000, "poll": false, "followSymlinks": false, "ignored": "**/.git" } ``` -------------------------------- ### Handle File System Change Events Source: https://github.com/webpack/watchpack/blob/main/README.md Listen for 'change' events to track modifications to watched files. The event provides the file path, its last modified time (mtime), and an explanation of how the change was detected. ```javascript wp.on("change", (filePath, mtime, explanation) => { // filePath: the changed file // mtime: last modified time for the changed file // explanation: textual information how this change was detected }); ``` -------------------------------- ### Handle File System Removal Events Source: https://github.com/webpack/watchpack/blob/main/README.md Listen for 'remove' events to detect when watched files or directories are deleted. The event includes the path of the removed item and an explanation. ```javascript wp.on("remove", (filePath, explanation) => { // filePath: the removed file or directory // explanation: textual information how this change was detected }); ``` -------------------------------- ### Watchpack Time Information Utilities Source: https://github.com/webpack/watchpack/blob/main/README.md Covers methods for collecting and retrieving time-related information about files and directories. ```APIDOC ## Watchpack Time Information Utilities ### Description These methods allow you to collect and access time-related metadata for files and directories being watched. ### `collectTimeInfoEntries(fileInfoEntries, directoryInfoEntries)` Collects time information for all known files and directories, including those not directly watched. #### Parameters - **fileInfoEntries** (Map) - A map to store file time information. The `Entry` object should have `safeTime` and `timestamp` properties. - **directoryInfoEntries** (Map) - A map to store directory time information. The `Entry` object should have a `safeTime` property. ### `getTimeInfoEntries()` Returns a map containing time information for all known files and directories. #### Returns - `Map` - A map where keys are absolute paths and values are objects containing `safeTime` and optionally `timestamp` (for files). ### `getTimes()` (Deprecated) Returns an object with all known change times for files. #### Returns - `Object` - An object where keys are file paths and values are their timestamps. ### Request Example ```javascript // Collecting time info const fileInfoEntries = new Map(); const directoryInfoEntries = new Map(); wp.collectTimeInfoEntries(fileInfoEntries, directoryInfoEntries); // Getting all time info entries const allTimeInfo = wp.getTimeInfoEntries(); // Getting old format of times (deprecated) const oldFileTimes = wp.getTimes(); ``` ``` -------------------------------- ### Watchpack Event Handling Source: https://github.com/webpack/watchpack/blob/main/README.md Explains the events emitted by Watchpack to notify about file system changes. ```APIDOC ## Watchpack Event Handling ### Description Watchpack emits events to inform about changes detected in the file system. ### `change` event Emitted when a file's content or existence changes. #### Parameters - **filePath** (string) - The path of the changed file. - **mtime** (number) - The last modified time of the changed file. - **explanation** (string) - Textual information about how the change was detected. ### `remove` event Emitted when a file or directory is removed. #### Parameters - **filePath** (string) - The path of the removed file or directory. - **explanation** (string) - Textual information about how the change was detected. ### `aggregated` event Emitted after a period of inactivity following one or more changes. #### Parameters - **changes** (Set) - A set of all changed file paths. - **removals** (Set) - A set of all removed file paths. ### Event Example ```javascript wp.on("change", (filePath, mtime, explanation) => { console.log(`File changed: ${filePath}`); }); wp.on("remove", (filePath, explanation) => { console.log(`File removed: ${filePath}`); }); wp.on("aggregated", (changes, removals) => { console.log("Aggregated changes:", changes); console.log("Aggregated removals:", removals); }); ``` ``` -------------------------------- ### Handle Change Events Source: https://context7.com/webpack/watchpack/llms.txt Listen for the change event to receive granular notifications about file or directory modifications before aggregation occurs. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); wp.on("change", (filePath, mtime, explanation) => { console.log("File changed:", filePath); console.log("Modified time:", new Date(mtime).toISOString()); console.log("Detection method:", explanation); // Output example: // File changed: /project/src/index.js // Modified time: 2024-01-15T10:30:45.000Z // Detection method: change }); wp.watch({ files: [path.join(__dirname, "src/index.js")], directories: [], }); ``` -------------------------------- ### Collect time info into separate Maps Source: https://context7.com/webpack/watchpack/llms.txt Populates provided Maps for files and directories separately. This is more efficient than getTimeInfoEntries when distinct handling of file and directory timestamps is required. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); wp.watch({ files: [], directories: [path.join(__dirname, "src")], }); setTimeout(() => { const fileTimestamps = new Map(); const directoryTimestamps = new Map(); wp.collectTimeInfoEntries(fileTimestamps, directoryTimestamps); console.log("=== File Timestamps ==="); for (const [filePath, entry] of fileTimestamps) { if (entry && entry.timestamp) { console.log(` ${path.relative(__dirname, filePath)}: ${entry.timestamp}`); } } console.log("\n=== Directory Timestamps ==="); for (const [dirPath, entry] of directoryTimestamps) { if (entry && entry.safeTime) { console.log(` ${path.relative(__dirname, dirPath)}: safeTime=${entry.safeTime}`); } } // Output example: // === File Timestamps === // src/index.js: 1705316445000 // src/utils.js: 1705312530000 // // === Directory Timestamps === // src: safeTime=1705316447000 // src/components: safeTime=1705316447000 }, 500); ``` -------------------------------- ### Ignored Option Patterns Source: https://context7.com/webpack/watchpack/llms.txt Configuration options for excluding files and directories from watching. ```APIDOC ## Ignored Option Patterns ### Description The ignored option supports multiple formats for excluding files and directories from watching. Paths are normalized to use forward slashes before pattern matching. ### Parameters - **ignored** (string | Array | RegExp | Function) - Optional - Pattern or function used to exclude files or directories from the watch list. ``` -------------------------------- ### Events: change and remove Source: https://context7.com/webpack/watchpack/llms.txt Event listeners for file system modifications and deletions. ```APIDOC ## Event: change ### Description Emitted when a file or directory changes. ### Response - **filePath** (string) - Path of the changed item. - **mtime** (number) - Modification time. - **explanation** (string) - Detection method. ## Event: remove ### Description Emitted when a watched file or directory is removed. ### Response - **filePath** (string) - Path of the removed item. - **explanation** (string) - Detection method. ``` -------------------------------- ### Collect Time Info Entries Source: https://github.com/webpack/watchpack/blob/main/README.md Populate time information for files and directories using `collectTimeInfoEntries`. This method processes both directly watched and indirectly known entries, storing safe times and timestamps. ```javascript // Watchpack.prototype.collectTimeInfoEntries(fileInfoEntries: Map, directoryInfoEntries: Map) wp.collectTimeInfoEntries(fileInfoEntries, directoryInfoEntries); // collects time info objects for all known files and directories // this include info from files not directly watched // key: absolute path, value: object with { safeTime, timestamp } // safeTime: a point in time at which it is safe to say all changes happened before that // timestamp: only for files, the mtime timestamp of the file ``` -------------------------------- ### Retrieve time information with getTimeInfoEntries Source: https://context7.com/webpack/watchpack/llms.txt Returns a Map containing safeTime, timestamp, and accuracy for all watched paths. Use this for cache invalidation and incremental build logic. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); wp.watch({ files: [ path.join(__dirname, "src/index.js"), path.join(__dirname, "src/utils.js"), ], directories: [path.join(__dirname, "src/components")], }); // Wait for initial scan to complete setTimeout(() => { const timeInfoEntries = wp.getTimeInfoEntries(); console.log("Time info for all watched paths:"); for (const [filePath, entry] of timeInfoEntries) { if (entry && entry.safeTime) { console.log(` ${path.basename(filePath)}:`); console.log(` safeTime: ${new Date(entry.safeTime).toISOString()}`); if (entry.timestamp) { console.log(` timestamp: ${new Date(entry.timestamp).toISOString()}`); } } } // Output example: // Time info for all watched paths: // index.js: // safeTime: 2024-01-15T10:30:47.000Z // timestamp: 2024-01-15T10:30:45.000Z // utils.js: // safeTime: 2024-01-15T09:15:32.000Z // timestamp: 2024-01-15T09:15:30.000Z }, 500); ``` -------------------------------- ### getTimeInfoEntries() Source: https://context7.com/webpack/watchpack/llms.txt Returns a Map containing time information for all watched files and directories, including safeTime, timestamp, and accuracy. ```APIDOC ## getTimeInfoEntries() ### Description Returns a Map containing time information for all watched files and directories. Each entry includes safeTime (safe to assume unchanged after this time), timestamp (mtime), and accuracy values. Useful for cache invalidation and incremental builds. ### Response - **Map** - A map where keys are file paths and values are objects containing safeTime, timestamp, and accuracy. ``` -------------------------------- ### Method: pause() Source: https://context7.com/webpack/watchpack/llms.txt Stops emitting events but keeps all watchers open for later resumption. Changes continue to be tracked internally. ```APIDOC ## Method: pause() ### Description Stops emitting events but keeps all watchers open for later resumption. Changes continue to be tracked internally and can be retrieved with getAggregated(). ``` -------------------------------- ### Retrieve legacy modification times Source: https://context7.com/webpack/watchpack/llms.txt Returns a simple object mapping paths to timestamps. This is a deprecated API; use getTimeInfoEntries instead for more detailed metadata. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); wp.watch({ files: [], directories: [path.join(__dirname, "src")], }); setTimeout(() => { const times = wp.getTimes(); console.log("File modification times:"); for (const [filePath, timestamp] of Object.entries(times)) { if (timestamp) { console.log(` ${path.relative(__dirname, filePath)}: ${new Date(timestamp).toISOString()}`); } } // Output example: // File modification times: // src/index.js: 2024-01-15T10:30:45.000Z // src/utils.js: 2024-01-15T09:15:30.000Z // src/components/Button.js: 2024-01-15T08:45:12.000Z }, 500); ``` -------------------------------- ### collectTimeInfoEntries() Source: https://context7.com/webpack/watchpack/llms.txt Collects time info entries into provided Maps for files and directories separately. ```APIDOC ## collectTimeInfoEntries() ### Description Collects time info entries into provided Maps for files and directories separately. More efficient than getTimeInfoEntries() when you need to distinguish between file and directory timestamps. ### Parameters - **fileTimestamps** (Map) - Required - Map to populate with file time information. - **directoryTimestamps** (Map) - Required - Map to populate with directory time information. ``` -------------------------------- ### Configure Polling Mode for Network Paths Source: https://context7.com/webpack/watchpack/llms.txt Use polling when native file watching is unreliable. The poll option accepts a boolean for default intervals or a number for custom millisecond intervals. ```javascript const Watchpack = require("watchpack"); const path = require("path"); // Enable polling with default interval (~5 seconds) const wp1 = new Watchpack({ aggregateTimeout: 1000, poll: true, }); // Enable polling with custom interval (10 seconds) const wp2 = new Watchpack({ aggregateTimeout: 1000, poll: 10000, // milliseconds }); // Watch network path with polling const networkPath = "/mnt/network-share/project"; wp2.on("aggregated", (changes) => { console.log("Changes detected on network path:", [...changes]); }); wp2.watch({ files: [], directories: [networkPath], }); console.log(`Watching network path with ${wp2.options.poll}ms polling interval`); // Alternatively, set environment variable: // WATCHPACK_POLLING=true node script.js // WATCHPACK_POLLING=5000 node script.js ``` -------------------------------- ### Method: close() Source: https://context7.com/webpack/watchpack/llms.txt Completely stops watching and closes all internal watchers. Frees system resources. ```APIDOC ## Method: close() ### Description Completely stops watching and closes all internal watchers. After calling close(), the Watchpack instance can no longer be used for watching. ``` -------------------------------- ### Handle Remove Events Source: https://context7.com/webpack/watchpack/llms.txt Listen for the remove event to detect when a watched file or directory is deleted from the filesystem. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); wp.on("remove", (filePath, explanation) => { console.log("File removed:", filePath); console.log("Detection method:", explanation); // Output example: // File removed: /project/src/deprecated.js // Detection method: rename }); wp.watch({ files: [ path.join(__dirname, "src/index.js"), path.join(__dirname, "src/deprecated.js"), ], directories: [], }); ``` -------------------------------- ### Close Watchpack Instance Source: https://context7.com/webpack/watchpack/llms.txt Completely stop all watching and free resources by calling `close()`. After closing, the Watchpack instance is unusable. This is essential for clean shutdowns. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); wp.on("aggregated", (changes, removals) => { console.log("Processing final changes..."); // Clean shutdown after processing wp.close(); console.log("Watcher closed, all resources freed"); }); wp.watch({ files: [path.join(__dirname, "src/index.js")], directories: [], }); // Or close on process exit process.on("SIGINT", () => { console.log("Shutting down..."); wp.close(); process.exit(0); }); ``` -------------------------------- ### getTimes() (Deprecated) Source: https://context7.com/webpack/watchpack/llms.txt Returns an object mapping file paths to their modification timestamps. ```APIDOC ## getTimes() ### Description Returns an object mapping file paths to their modification timestamps. This is a legacy API; prefer getTimeInfoEntries() for more detailed information including safeTime and accuracy. ### Response - **Object** - An object mapping file paths to their modification timestamps. ``` -------------------------------- ### Pause and Resume Watchpack Events Source: https://context7.com/webpack/watchpack/llms.txt Temporarily stop emitting events using `pause()` while keeping watchers active. Changes are tracked internally and can be retrieved with `getAggregated()`. Resume watching with `watch()` to continue event processing. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, }); // Pause during build process to collect changes function performBuild() { console.log("Build started, pausing watcher..."); wp.pause(); // Simulate build process setTimeout(() => { // Get all changes that occurred during build const { changes, removals } = wp.getAggregated(); console.log("Changes during build:", [...changes]); console.log("Removals during build:", [...removals]); console.log("Build complete, resuming watch..."); // Resume watching with same files/directories wp.watch({ files: [], directories: [path.join(__dirname, "src")], }); }, 2000); } wp.on("aggregated", (changes) => { if (changes.size > 0) { performBuild(); } }); wp.watch({ files: [], directories: [path.join(__dirname, "src")], }); ``` -------------------------------- ### Close Watchers Source: https://github.com/webpack/watchpack/blob/main/README.md Call `close()` to stop emitting events and terminate all active file system watchers. This should be used when Watchpack is no longer needed. ```javascript // Watchpack.prototype.close() wp.close(); // stops emitting events and closes all watchers ``` -------------------------------- ### Handle Aggregated Events with Watchpack Source: https://context7.com/webpack/watchpack/llms.txt Listen for the 'aggregated' event to process batches of file changes and removals after a period of inactivity. The `aggregateTimeout` option controls this delay. Sets of changes and removals are provided, allowing direct modification. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 1000, // Wait 1 second after last change }); wp.on("aggregated", (changes, removals) => { console.log("=== Aggregated Changes ==="); console.log("Changed files:", [...changes]); console.log("Removed files:", [...removals]); // Process batch of changes efficiently if (changes.size > 0) { console.log(`Rebuilding ${changes.size} changed file(s)...`); for (const file of changes) { // Trigger rebuild for each changed file console.log(" - Rebuild:", path.basename(file)); } } if (removals.size > 0) { console.log(`Cleaning up ${removals.size} removed file(s)...`); } // Output example: // === Aggregated Changes === // Changed files: ['/project/src/index.js', '/project/src/utils.js'] // Removed files: [] // Rebuilding 2 changed file(s)... // - Rebuild: index.js // - Rebuild: utils.js }); wp.watch({ files: [], directories: [path.join(__dirname, "src")], }); ``` -------------------------------- ### Pause and Resume Watching Source: https://github.com/webpack/watchpack/blob/main/README.md Use `pause()` to temporarily stop emitting events while keeping watchers active. Events are aggregated during the pause and can be retrieved later. Resuming is implicit when `watch` is called again. ```javascript // Watchpack.prototype.pause() wp.pause(); // stops emitting events, but keeps watchers open // next "watch" call can reuse the watchers // The watcher will keep aggregating events // which can be received with getAggregated() ``` -------------------------------- ### Method: getAggregated() Source: https://context7.com/webpack/watchpack/llms.txt Returns current aggregated changes and removals as Sets, clearing them from the watcher. ```APIDOC ## Method: getAggregated() ### Description Returns current aggregated changes and removals as Sets, clearing them from the watcher. Cancels any pending aggregation timer. ### Response - **changes** (Set) - The current set of changed files. - **removals** (Set) - The current set of removed files. ``` -------------------------------- ### Retrieve Aggregated Changes with getAggregated() Source: https://context7.com/webpack/watchpack/llms.txt Manually retrieve current aggregated changes and removals using `getAggregated()`. This method clears pending changes and cancels any active aggregation timer. Useful for checking status while paused or on demand. ```javascript const Watchpack = require("watchpack"); const path = require("path"); const wp = new Watchpack({ aggregateTimeout: 5000, // Long timeout }); wp.watch({ files: [], directories: [path.join(__dirname, "src")], }); // Manual aggregation check (e.g., triggered by user command) function checkForChanges() { const { changes, removals } = wp.getAggregated(); if (changes.size === 0 && removals.size === 0) { console.log("No pending changes"); return null; } console.log("Pending changes:", changes.size); console.log("Pending removals:", removals.size); return { changedFiles: [...changes], removedFiles: [...removals], }; // Output example: // Pending changes: 3 // Pending removals: 1 } // Check every 2 seconds regardless of aggregateTimeout setInterval(checkForChanges, 2000); ``` -------------------------------- ### Handle Aggregated Changes Source: https://github.com/webpack/watchpack/blob/main/README.md Subscribe to the 'aggregated' event to receive batches of changes and removals after a period of inactivity. This is useful for debouncing operations that depend on multiple file system events. ```javascript wp.on("aggregated", (changes, removals) => { // changes: a Set of all changed files // removals: a Set of all removed files // watchpack gives up ownership on these Sets. }); ``` -------------------------------- ### Retrieve Aggregated Changes Source: https://github.com/webpack/watchpack/blob/main/README.md Use `getAggregated()` to retrieve the current set of aggregated changes and removals. This method also clears the internal aggregated data, ensuring subsequent calls only return new events. ```javascript // Watchpack.prototype.getAggregated(): { changes: Set, removals: Set } const { changes, removals } = wp.getAggregated(); // returns the current aggregated info and removes that from the watcher // The next aggregated event won't include that info and will only emitted // when futher changes happen // Can also be used when paused. ``` -------------------------------- ### Event: aggregated Source: https://context7.com/webpack/watchpack/llms.txt Emitted after the aggregateTimeout period when no new changes occur. Provides Sets of all changed and removed paths since the last aggregated event. ```APIDOC ## Event: aggregated ### Description Emitted after the aggregateTimeout period when no new changes occur. Watchpack transfers ownership of the Sets, allowing direct modification. ### Parameters - **changes** (Set) - Set of paths that have changed. - **removals** (Set) - Set of paths that have been removed. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.