npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2022 – Pkg Stats / Ryan Hefner

ts-resolve

v0.1.0

Published

Resolve typescript ES modules

Downloads

15

Readme

ts-resolve

npm version CI Coverage Status code style: prettier types MIT license

Resolve typescript ES modules

Overview

This package will resolve typescript ES modules. It is mainly built for usage in the resolve hook of a node loader but the API should be generic enough to be useful in other scenarions.

For relative and absolute paths it is easy to resolve typescript files from their javascript counterpart, just change the file extension to .ts or .tsx. However for bare specifiers it is a bit more tricky. Most of the time a bare specifier will resolve to a package installed into node_modules that is not part of your source code. But if you are using project references and yarn/npm workspaces then bare specifiers may point to a package that is part of your project.

The aim of this package is to resolve all cases including:

  • Relative and absolute paths
  • Bare specifiers for packages specified as project references in a npm/yarn workspace
  • Bare specifiers resolved by the base and path options in tsconfig.json.

How to install

yarn add --dev ts-resolve

API

tsResolve

export function tsResolve(
  specifier: string,
  context: { parentURL: string | undefined; conditions: ReadonlyArray<string> },
  tsConfig: string,
  fileSystem?: FileSystem | undefined
): { fileUrl: string; tsConfigUrl: string } | undefined;

Resolves a specifier.

Input

  • specifier - A specifier to resolve, eg. ./foo/bar.js or @myapp/package-a.
  • context.parentURL - The URL which is the parent of the resolve (normally the file that does the import of the specifier). Relative resolves will resolve relative to the parent URL path. Is undefined for the entry file since it has no parent.
  • context.conditions - Conditions for resolve.
  • tsConfig - A tsconfig.json file. In the case of project references it does not have to be the actual tsconfig.json that is associated with the resolved file, but it does have to have a reference to the tsconfig.json that is associated with the resolved file. So if you have a main tsconfig.json that references every other tsconfig.json in the workspace, you can use it for all calls.
  • fileSystem - Optional. An object with filesystem methods. Could be used for testing or in scenarios where you don't want to make lookups in the normal filesystem. If it is not provided then a default implementation that reads the normal filesystem will be used.
    • cwd: () => string
    • isFile: (path: string) => boolean
    • isDirectory: (path: string) => boolean
    • getRealpath: (path: string) => string | undefined;
    • readFile: (filename: string) => string | undefined

Returns

An object with keys:

  • fileUrl - URL to the resolved file. If the resolved specifier was found to be created from compiling a typescript file then this will be that typescript file.
  • tsConfigUrl - URL for the tsconfig.json that is associated with the resolved file. Useful if you want to transpile the resolved file.

How to use with a loader

You can use this package as a part of build a transpiling node loader for typescript. Here is an example using esbuild for the transpile:

// file loader.mjs
import { fileURLToPath } from "url";
import { transformSync } from "esbuild";
import { tsResolve } from "ts-resolve";

export function resolve(specifier, context, defaultResolve) {
  const entryTsConfig = process.env["TS_NODE_PROJECT"];
  if (entryTsConfig === undefined || entryTsConfig === null || entryTsConfig === "") {
    throw new Error("Entry tsconfig file must be present in TS_NODE_PROJECT.");
  }
  const resolved = tsResolve(specifier, context, entryTsConfig);
  if (resolved !== undefined) {
    const { fileUrl, tsConfigUrl } = resolved;
    return { url: fileUrl, format: tsConfigUrl };
  }
  return defaultResolve(specifier, context, defaultResolve);
}

export async function load(url, context, defaultLoad) {
  // Return transpiled source if typescript file
  if (isTypescriptFile(url)) {
    // Call defaultLoad to get the source
    const format = "module";
    const { source: rawSource } = await defaultLoad(url, { format }, defaultLoad);
    const source = transpileTypescript(url, rawSource, "esm");
    return { format, source };
  }
  // Let Node.js load it
  return defaultLoad(url, context);
}

function isTypescriptFile(url) {
  const extensionsRegex = /\.ts$/;
  return extensionsRegex.test(url);
}

const isWindows = process.platform === "win32";

function transpileTypescript(url, source, outputFormat) {
  let filename = url;
  if (!isWindows) filename = fileURLToPath(url);

  const {
    code: js,
    warnings,
    map: jsSourceMap,
  } = transformSync(source.toString(), {
    sourcefile: filename,
    sourcemap: "both",
    loader: "ts",
    target: "esnext",
    // This sets the output format for the generated JavaScript files
    // format: format === "module" ? "esm" : "cjs",
    format: outputFormat,
  });

  if (warnings && warnings.length > 0) {
    for (const warning of warnings) {
      console.log(warning.location);
      console.log(warning.text);
    }
  }

  return js;
}

Then you can use it like this:

node --loader loader.mjs myfile.ts