AukeA
Denoβ€’2y agoβ€’
7 replies
Auke

Setup for using npm packages locally + via server.ts

Hi Deno,

I have a project in which I use Deno both to execute
ts
/js files locally to compute features, using a command like:
deno run --allow-all --v8-flags=--max-old-space-size=2192 compute.ts
This compute.ts script uses
.js
scripts that are also used in a webpage I serve using a simple
server.ts
file, which I serve using deno:
deno run -A server.ts

which contains the following code to serve files:
Deno.serve((req: Request) => {
  let pathname = new URL(req.url).pathname;

  // fonts endpoint
  if (pathname.startsWith("/fonts")) {
    return fonts_endpoint(req, pathname);
  }

  // Canonicalize path
  if (pathname === "/" || pathname === "") {
    pathname = "/index.html";
  }
  const filepath = "." + pathname;
  console.log(filepath);

  const isReadableFile = existsSync(filepath, {
    isReadable: true,
    isFile: true,
  });

  if (isReadableFile) {
    return serveFile(req, filepath);
  }

  // Otherwise the requested resource is not available
  return new Response("404: Not Found", {
    status: 404,
  });
});

and serves plain html,
.js
and .ttf files.

I have this setup working for a long time, but it is a mess - I have installed
npm
libraries using
npm
, access those javascript files by using direct paths:
import * as FloBezier from "./node_modules/flo-bezier3/browser/index.js";
and I do this as a solution to have this javascript file working both locally (using deno run cli) and when accessing the file through the browser (using the server.ts above).

Is there a more cannonical approach to doing this? Key requirement is being able to use the same js file both locally and in the browser
Was this page helpful?