Skip to main content

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.177.0/http/mod.ts";
import { serveDirWithTs } from "https://deno.land/x/ts_serve@v1.4.4/mod.ts";

serve((request) => serveDirWithTs(request));
// index.html
<script src="./main.ts" type="module"></script>;

// main.ts
console.log(1);
  • Supports ts, tsx and jsx transpiling.
  • The URL remains *.ts and will not be rewritten. That is, import "./foo.ts" and <script src="./foo.ts" type="module"> work on browser.
  • You can use import "./foo.ts", which has the same syntax as Deno. This means that you can use the completion and diagnostic features for frontend code by installing the Deno and Deno extensions in your editor.

Usage

As oak middleware:

import { Application } from "https://deno.land/x/oak@v11.1.0/mod.ts";
import { tsMiddleware } from "https://deno.land/x/ts_serve@v1.4.4/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.177.0/http/mod.ts";
import { serveDirWithTs } from "https://deno.land/x/ts_serve@v1.4.4/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.177.0/http/mod.ts";
import { serveFileWithTs } from "https://deno.land/x/ts_serve@v1.4.4/mod.ts";

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

As Hono’s handler:

import { serve } from "https://deno.land/std@0.177.0/http/server.ts";
import { Hono } from "https://deno.land/x/hono@v2.2.5/mod.ts";
import { serveDirWithTs } from "https://deno.land/x/ts_serve@v1.4.4/mod.ts";

const app = new Hono();
app.get("*", (c) => {
  return serveDirWithTs(c.req);
});
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.177.0/http/mod.ts";
import {
  fourceInstantiateWasm,
  serveDirWithTs,
} from "https://deno.land/x/ts_serve@v1.4.4/mod.ts";

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

develop

> deno task test