Skip to content

Commit

Permalink
add file watching to JS API (FredKSchott#1452)
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott authored and peterhpchen committed Oct 31, 2020
1 parent ea3f05f commit 3411a53
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
6 changes: 6 additions & 0 deletions snowpack/src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import {
SnowpackBuildMap,
LoadResult,
SnowpackDevServer,
OnFileChangeCallback,
} from '../types/snowpack';
import {
BUILD_CACHE,
Expand Down Expand Up @@ -1335,9 +1336,13 @@ export async function startDevServer(commandOptions: CommandOptions): Promise<Sn
// Defer "chokidar" loading to here, to reduce impact on overall startup time
const chokidar = await import('chokidar');

// Allow the user to hook into this callback, if they like (noop by default)
let onFileChangeCallback: OnFileChangeCallback = () => {};

// Watch src files
async function onWatchEvent(fileLoc: string) {
logger.info(colors.cyan('File changed...'));
onFileChangeCallback({filePath: fileLoc});
const updatedUrl = getUrlForFile(fileLoc, config);
if (updatedUrl) {
handleHmrUpdate(fileLoc, updatedUrl);
Expand Down Expand Up @@ -1407,6 +1412,7 @@ export async function startDevServer(commandOptions: CommandOptions): Promise<Sn
handleRequest,
sendResponseFile,
sendResponseError,
onFileChange: (callback) => (onFileChangeCallback = callback),
async shutdown() {
await watcher.close();
server.close();
Expand Down
2 changes: 2 additions & 0 deletions snowpack/src/types/snowpack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export interface LoadResult<T = Buffer | string> {
checkStale?: () => Promise<void>;
}

export type OnFileChangeCallback = ({filePath: string}) => any;
export interface SnowpackDevServer {
port: number;
loadUrl: {
Expand Down Expand Up @@ -59,6 +60,7 @@ export interface SnowpackDevServer {
{contents, originalFileLoc, responseFileName}: LoadResult,
) => void;
sendResponseError: (req: http.IncomingMessage, res: http.ServerResponse, status: number) => void;
onFileChange: (callback: OnFileChangeCallback) => void;
shutdown(): Promise<void>;
}

Expand Down

0 comments on commit 3411a53

Please sign in to comment.