Skip to content

Instantly share code, notes, and snippets.

@jrson83
Forked from modeware/server.js
Created October 14, 2023 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrson83/e29e7762056060d193413aab5633c8aa to your computer and use it in GitHub Desktop.
Save jrson83/e29e7762056060d193413aab5633c8aa 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