ts-to-html
Version:
TS and SASS compiler for a HTML with live preview
47 lines (46 loc) • 2.02 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
const ws_1 = require("ws");
const compiler_1 = require("./utils/compiler");
const log_1 = require("./utils/log");
const server_1 = __importDefault(require("./utils/server"));
// Compile files
(async () => await (0, compiler_1.compileAll)())();
// Server instance
const cb = () => (0, log_1.clearAndLog)("Waiting for changes...".cyan);
const server = (0, server_1.default)(cb);
// WebSocket
const wss = new ws_1.WebSocketServer({ server });
wss.on('connection', ws => {
ws.on('error', console.error);
ws.on('unexpected-response', console.error);
});
wss.on('error', console.error);
// Watchers
const watcher = (0, node_fs_1.watch)((0, node_path_1.resolve)(), { recursive: true });
watcher.on('change', async (_, fn) => {
const filename = fn ? typeof fn === "string" ? fn : fn.toString() : "";
// Check changed folder
if (/^(?:public|src)[\\/][^\\/]+$/.test(filename)) {
// Send to websocket
if (/^public[\\/]index\.(html|htm|shtml)$/.test(filename)) {
wss.clients.forEach(ws => ws.send(JSON.stringify({ type: "reload" })));
}
else if (/^public[\\/][^\\/]+\.scss$/.test(filename)) {
// Compile SASS files
const path = (0, node_path_1.resolve)(process.cwd(), filename);
const compiled = await (0, compiler_1.compileSassFile)(path);
const resultPath = path.replace(/\.scss$/, ".css");
(0, node_fs_1.writeFileSync)(resultPath, compiled);
wss.clients.forEach(ws => ws.send(JSON.stringify({ type: "update", data: "css" })));
}
else {
wss.clients.forEach(ws => ws.send(JSON.stringify({ filename })));
}
}
});