Skip to content

Instantly share code, notes, and snippets.

@modeware
Created September 25, 2023 03:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save modeware/725783cd2bc7ceaa30c4308aaae65967 to your computer and use it in GitHub Desktop.
Save modeware/725783cd2bc7ceaa30c4308aaae65967 to your computer and use it in GitHub Desktop.
Run a .ts extension file on a browser (Was wondering how vite was able to run a ts file on a browser, in memory transpilation, browser only cares for the header that tells file type.)
var http = require("http");
var { readFileSync } = require("fs");
var path = require("path");
//create a server object:
http
.createServer(function (req, res) {
if (req.method === "GET" && req.url == "/") {
const file = readFileSync(path.join(__dirname, "/index.html"));
res.writeHead(200, { "Content-Type": "text/html" });
res.write(file); //write a response to the client
res.end();
}
if (req.method === "GET" && req.url == "/src/index.ts") {
console.log("DOne");
const esbuild = require("esbuild");
const inputFileName = "src/index.ts"; // Your ts file
esbuild
.build({
entryPoints: [inputFileName],
bundle: true, // Bundle the output into a single file
write: false
})
.then((result) => {
res.writeHead(200, { "Content-Type": "application/javascript" }); // This causes the browser to treat it as JS
console.log("Transpilation completed successfully!", result.outputFiles[0].text);
res.write(result.outputFiles[0].text);
res.end();
})
.catch((error) => {
console.error("Error during transpilation:", error);
});
}
})
.listen(8080, () => console.log("8080")); //the server object listens on port 8080
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment