-
-
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.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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