Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HMR #25

Merged
merged 20 commits into from
Sep 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@

#generated manifest
public/manifest.json
utils/reload/*.js
utils/reload/injections/*.js
12 changes: 9 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@
},
"scripts": {
"build": "tsc --noEmit && vite build",
"dev": "nodemon",
"build:hmr": "rollup --config utils/reload/rollup.config.ts",
"wss": "node utils/reload/initReloadServer.js",
"dev": "yarn build:hmr && (yarn wss & nodemon)",
"test": "jest"
},
"type": "module",
Expand All @@ -18,15 +20,18 @@
"react-dom": "18.2.0"
},
"devDependencies": {
"@rollup/plugin-typescript": "^8.5.0",
"@testing-library/react": "^13.3.0",
"@types/chrome": "0.0.193",
"@types/jest": "^28.1.6",
"@types/node": "18.0.6",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"@types/ws": "^8.5.3",
"@typescript-eslint/eslint-plugin": "5.30.6",
"@typescript-eslint/parser": "5.30.6",
"@vitejs/plugin-react": "2.0.0",
"chokidar": "^3.5.3",
"eslint": "8.20.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "4.2.1",
Expand All @@ -36,11 +41,12 @@
"jest-environment-jsdom": "^28.1.3",
"nodemon": "2.0.19",
"prettier": "2.7.1",
"rollup": "^2.79.0",
"sass": "1.53.0",
"ts-jest": "28.0.7",
"ts-loader": "9.3.1",
"ts-node": "10.9.1",
"typescript": "4.7.4",
"vite": "3.0.1"
"vite": "3.0.1",
"ws": "^8.8.1"
}
}
10 changes: 10 additions & 0 deletions src/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ declare namespace chrome {
export default Chrome;
}

declare module "virtual:reload-on-update-in-background-script" {
export const reloadOnUpdate: (watchPath: string) => void;
export default reloadOnUpdate;
}

declare module "virtual:reload-on-update-in-view" {
const refreshOnUpdate: (watchPath: string) => void;
export default refreshOnUpdate;
}

declare module "*.svg" {
import React = require("react");
export const ReactComponent: React.SFC<React.SVGProps<SVGSVGElement>>;
Expand Down
4 changes: 4 additions & 0 deletions src/pages/background/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
import reloadOnUpdate from "virtual:reload-on-update-in-background-script";

reloadOnUpdate("pages/background");

console.log("background loaded");
3 changes: 3 additions & 0 deletions src/pages/content/components/Demo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { createRoot } from "react-dom/client";
import App from "@src/pages/content/components/Demo/app";
import refreshOnUpdate from "virtual:reload-on-update-in-view";

refreshOnUpdate("pages/content/components/Demo");

const root = document.createElement("div");
root.id = "chrome-extension-boilerplate-react-vite-content-view-root";
Expand Down
3 changes: 3 additions & 0 deletions src/pages/newtab/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import React from "react";
import { createRoot } from "react-dom/client";
import Newtab from "@pages/newtab/Newtab";
import "@pages/newtab/index.css";
import refreshOnUpdate from "virtual:reload-on-update-in-view";

refreshOnUpdate("pages/newtab");

function init() {
const appContainer = document.querySelector("#app-container");
Expand Down
3 changes: 3 additions & 0 deletions src/pages/options/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import React from "react";
import { createRoot } from "react-dom/client";
import Options from "@pages/options/Options";
import "@pages/options/index.css";
import refreshOnUpdate from "virtual:reload-on-update-in-view";

refreshOnUpdate("pages/options");

function init() {
const appContainer = document.querySelector("#app-container");
Expand Down
3 changes: 3 additions & 0 deletions src/pages/panel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import React from "react";
import { createRoot } from "react-dom/client";
import Panel from "@pages/panel/Panel";
import "@pages/panel/index.css";
import refreshOnUpdate from "virtual:reload-on-update-in-view";

refreshOnUpdate("pages/panel");

function init() {
const appContainer = document.querySelector("#app-container");
Expand Down
3 changes: 3 additions & 0 deletions src/pages/popup/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import React from "react";
import { createRoot } from "react-dom/client";
import "@pages/popup/index.css";
import Popup from "@pages/popup/Popup";
import refreshOnUpdate from "virtual:reload-on-update-in-view";

refreshOnUpdate("pages/popup");

function init() {
const appContainer = document.querySelector("#app-container");
Expand Down
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@
"allowSyntheticDefaultImports": true,
"lib": ["dom", "dom.iterable", "esnext"],
"forceConsistentCasingInFileNames": true,
"typeRoots": ["./src/global.d.ts"],
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curios what is it about

"paths": {
"@src/*": ["src/*"],
"@assets/*": ["src/assets/*"],
"@pages/*": ["src/pages/*"]
"@pages/*": ["src/pages/*"],
"virtual:reload-on-update-in-background-script": ["./src/global.d.ts"],
"virtual:reload-on-update-in-view": ["./src/global.d.ts"]
}
},
"include": ["src", "utils", "vite.config.ts", "node_modules/@types"]
Expand Down
50 changes: 50 additions & 0 deletions utils/plugins/add-hmr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as path from "path";
import { PluginOption } from "vite";
import { readFileSync } from "fs";

const isDev = process.env.__DEV__ === "true";

const DUMMY_CODE = `export default function(){};`;

function getInjectionCode(fileName: string): string {
return readFileSync(
path.resolve(__dirname, "..", "reload", "injections", fileName),
{ encoding: "utf8" }
);
}

type Config = {
background?: boolean;
view?: boolean;
};

export default function addHmr(config?: Config): PluginOption {
const { background = false, view = true } = config || {};
const idInBackgroundScript = "virtual:reload-on-update-in-background-script";
const idInView = "virtual:reload-on-update-in-view";

const scriptHmrCode = isDev ? getInjectionCode("script.js") : DUMMY_CODE;
const viewHmrCode = isDev ? getInjectionCode("view.js") : DUMMY_CODE;

return {
name: "add-hmr",
resolveId(id) {
if (id === idInBackgroundScript || id === idInView) {
return getResolvedId(id);
}
},
load(id) {
if (id === getResolvedId(idInBackgroundScript)) {
return background ? scriptHmrCode : DUMMY_CODE;
}

if (id === getResolvedId(idInView)) {
return view ? viewHmrCode : DUMMY_CODE;
}
},
};
}

function getResolvedId(id: string) {
return "\0" + id;
}
5 changes: 5 additions & 0 deletions utils/reload/constant.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const LOCAL_RELOAD_SOCKET_PORT = 8081;
export const LOCAL_RELOAD_SOCKET_URL = `ws://localhost:${LOCAL_RELOAD_SOCKET_PORT}`;
export const UPDATE_PENDING_MESSAGE = "wait_update";
export const UPDATE_REQUEST_MESSAGE = "do_update";
export const UPDATE_COMPLETE_MESSAGE = "done_update";
57 changes: 57 additions & 0 deletions utils/reload/initReloadClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import {
LOCAL_RELOAD_SOCKET_URL,
UPDATE_COMPLETE_MESSAGE,
UPDATE_PENDING_MESSAGE,
UPDATE_REQUEST_MESSAGE,
} from "./constant";
import { Interpreter } from "./interpreter";

let needToUpdate = false;

export default function initReloadClient({
watchPath,
onUpdate,
}: {
watchPath: string;
onUpdate: () => void;
}): WebSocket {
const socket = new WebSocket(LOCAL_RELOAD_SOCKET_URL);

function sendUpdateCompleteMessage() {
socket.send(Interpreter.Send({ type: UPDATE_COMPLETE_MESSAGE }));
}

socket.addEventListener("message", (event) => {
const message = Interpreter.Receive(String(event.data));

switch (message.type) {
case UPDATE_REQUEST_MESSAGE: {
if (needToUpdate) {
sendUpdateCompleteMessage();
needToUpdate = false;
onUpdate();
}
return;
}
case UPDATE_PENDING_MESSAGE: {
needToUpdate = checkUpdateIsNeeded({
watchPath,
updatedPath: message.path,
});
return;
}
}
});

return socket;
}

function checkUpdateIsNeeded({
watchPath,
updatedPath,
}: {
updatedPath: string;
watchPath: string;
}): boolean {
return updatedPath.includes(watchPath);
}
70 changes: 70 additions & 0 deletions utils/reload/initReloadServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { WebSocketServer, WebSocket } from "ws";
import chokidar from "chokidar";
import { clearTimeout } from "timers";
import {
LOCAL_RELOAD_SOCKET_PORT,
UPDATE_COMPLETE_MESSAGE,
UPDATE_PENDING_MESSAGE,
UPDATE_REQUEST_MESSAGE,
} from "./constant";
import { Interpreter } from "./interpreter";

const clientsThatNeedToUpdate: Set<WebSocket> = new Set();

function initReloadServer() {
const wss = new WebSocketServer({ port: LOCAL_RELOAD_SOCKET_PORT });

wss.on("connection", (ws) => {
clientsThatNeedToUpdate.add(ws);

ws.addEventListener("close", () => clientsThatNeedToUpdate.delete(ws));
ws.addEventListener("message", (event) => {
const message = Interpreter.Receive(String(event.data));
if (message.type === UPDATE_COMPLETE_MESSAGE) {
ws.close();
}
});
});
}

/** CHECK:: src file was updated **/
chokidar.watch("src").on("all", (event, path) => {
debounce(sendPendingUpdateMessageToAllSockets, 200)(path);
});

function sendPendingUpdateMessageToAllSockets(path: string) {
const _sendPendingUpdateMessage = (ws: WebSocket) =>
sendPendingUpdateMessage(ws, path);

clientsThatNeedToUpdate.forEach(_sendPendingUpdateMessage);
}

function sendPendingUpdateMessage(ws: WebSocket, path: string) {
ws.send(Interpreter.Send({ type: UPDATE_PENDING_MESSAGE, path }));
}

/** CHECK:: build was completed **/
chokidar.watch("dist").on("all", () => {
debounce(sendUpdateMessageToAllSockets, 200);
});

function sendUpdateMessageToAllSockets() {
clientsThatNeedToUpdate.forEach(sendUpdateMessage);
}

function sendUpdateMessage(ws: WebSocket) {
ws.send(Interpreter.Send({ type: UPDATE_REQUEST_MESSAGE }));
}

function debounce<A extends unknown[]>(
callback: (...args: A) => void,
delay: number
) {
let timer: NodeJS.Timeout;
return function (...args: A) {
clearTimeout(timer);
timer = setTimeout(() => callback(...args), delay);
};
}

initReloadServer();
12 changes: 12 additions & 0 deletions utils/reload/injections/script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import initReloadClient from "../initReloadClient";

export default function addHmrIntoScript(watchPath: string) {
initReloadClient({
watchPath,
onUpdate: () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
chrome.runtime.reload();
},
});
}
29 changes: 29 additions & 0 deletions utils/reload/injections/view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import initReloadClient from "../initReloadClient";

export default function addHmrIntoView(watchPath: string) {
let pendingReload = false;

initReloadClient({
watchPath,
onUpdate: () => {
// disable reload when tab is hidden
if (document.hidden) {
pendingReload = true;
return;
}
reload();
},
});

// reload
function reload(): void {
pendingReload = false;
window.location.reload();
}

// reload when tab is visible
function reloadWhenTabIsVisible(): void {
!document.hidden && pendingReload && reload();
}
document.addEventListener("visibilitychange", reloadWhenTabIsVisible);
}
Loading