ayame113 / ts-serve

Transpile TypeScript on the fly and deliver it from your server as ES Modules.
https://deno.land/x/ts_serve
MIT License
39 stars 2 forks source link
deno deno-deploy denodeploy

ts-serve

Test codecov

TypeScript + ES Modules

Transpile TypeScript on the fly and serve it from your server as ES Modules.

import { serve } from "https://deno.land/std@0.178.0/http/mod.ts";
import { serveDirWithTs } from "https://deno.land/x/ts_serve@$MODULE_VERSION/mod.ts";

serve((request) => serveDirWithTs(request));
// index.html
<script src="https://github.com/ayame113/ts-serve/raw/main/main.ts" type="module"></script>;

// main.ts
console.log(1);

Usage

As oak middleware:

import { Application } from "https://deno.land/x/oak@v12.0.1/mod.ts";
import { tsMiddleware } from "https://deno.land/x/ts_serve@$MODULE_VERSION/mod.ts";

const app = new Application();

// use middleware and transpile TS code
app.use(tsMiddleware);

// serve static file
app.use(async (ctx, next) => {
  try {
    await ctx.send({ root: "./" });
  } catch {
    await next();
  }
});
await app.listen({ port: 8000 });

As a replacement for the serveDir function in the Deno standard library:

import { serve } from "https://deno.land/std@0.178.0/http/mod.ts";
import { serveDirWithTs } from "https://deno.land/x/ts_serve@$MODULE_VERSION/mod.ts";

serve((request) => serveDirWithTs(request));

As a replacement for the serveFile function in the Deno standard library:

import { serve } from "https://deno.land/std@0.178.0/http/mod.ts";
import { serveFileWithTs } from "https://deno.land/x/ts_serve@$MODULE_VERSION/mod.ts";

serve((request) => serveFileWithTs(request, "./mod.ts"));

As Hono's handler:

import { serve } from "https://deno.land/std@0.178.0/http/server.ts";
import { Hono } from "https://deno.land/x/hono@v3.0.2/mod.ts";
import { serveDirWithTs } from "https://deno.land/x/ts_serve@$MODULE_VERSION/mod.ts";

const app = new Hono();
app.get("*", (c) => {
  return serveDirWithTs(c.req.raw);
});
serve(app.fetch);

fourceInstantiateWasm function

Calling this function will load the wasm file used in the deno_emit of the dependency. Even if you don't call this function, if you call the transpile function, the wasm file will be read automatically at that timing.

However, performance can be an issue on the server as loading the wasm file takes time. In that case, calling this function in advance can speed up later calls to the transpile function.

import { serve } from "https://deno.land/std@0.178.0/http/mod.ts";
import {
  fourceInstantiateWasm,
  serveDirWithTs,
} from "https://deno.land/x/ts_serve@$MODULE_VERSION/mod.ts";

// load the wasm file in the background when the server starts.
fourceInstantiateWasm();
serve((request) => serveDirWithTs(request));

develop

> deno task test