2

I'm creating a TS library the build for which involves parsing TS code, generating types and additional variables from it in a complex and custom process (ie, not just by running it through a compiling tool).

Specifically, this lib is a set of OpenAPI specs for several different APIs. It's written in TS, and various TS files within the lib export OpenAPI specs which are basically big JSON blobs coming from a TS file. Then I process those blobs using a manual/bespoke compilation process, and turn them into a series of exports, both of endpoint response types and sub-types. None of this can be auto-compiled using tsc, webpack, etc, so I'm aiming to mimic the output shape of such a process with a "manual" compilation script described.

I'm then importing the resulting lib it into a React app which uses TypeScript, and also has Jest tests. Notably, my library doesn't have a default export, because it represents several APIs, and so, rather, is imported like import { SomeAPI } from "my-lib/dist/some-api";. (I'd love to get rid of the /dist/, but one thing at a time.)

I'm running into issues figuring out how to structure my built code so that it can be imported and run by both the app and the app's Jest specs.

My first attempt was to compile everything to just .ts files, which export both variables and types. This worked fine for the app, but threw a cannot use import statement outside of a module error when I tried to import the library and run the specs in the "importing" app, because Jest doesn't babel-process node_modules by default. I could try to get the app to transpile my lib when running the tests -- per Jest's error message, To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. -- but that seems wrong. Shouldn't the lib be in a directly consumable format when compiled?

Attempts to fix this by declaring "type": "module" in the library package.json file then led my custom compiling script, which is run using ts-node, to throw an Unknown file extension ".ts" error. Attempts to fix this by using ts-node's ESM option led to other issues.

So I took a step back and thought it would be better to split my files into .ts files which use module.exports to export plain JS objects/variables, and accompanying .d.ts files which export matching types with the same name (after reading this SO Post).

That didn't work, either, as I'm now getting warnings that my imported files are not modules, and the types don't appear to be recognized by the importing app at all.

So I'm a little stumped, and wanted to get a sense of what I should be doing here. If I'm exporting a library for consumption in a TS app, what should my export look like?

Is it correct to have .ts and .d.ts files side by side, with the .d.ts files exporting (using export/import syntax) the types for the neighboring variables (exported using modules.export syntax)? Or should I have a parallel types directory exporting just the types? If so, how will the consuming app map types to variables? Should the variable files be .js instead? Do I need to set "type": "module" in my package.json? Etc.

I've tried looking at the code of some other TS libraries, but they all seem to do complex and bespoke things, which are frankly hard to understand. (Eg, I looked at lodash, and there's some strange magic going on there). Is there a basic best-practice here?

Here are some of the relevant files (trimmed down) to give a sense of where I'm currently at:

package.json

{
  "version": "1.0.2",
  "files": [
    "./dist"
  ],
  "scripts": {
    "compile:openapi": "ts-node scripts/compileOpenapi.ts"
  },
  "engines": {
    "node": "^16.14.0"
  }
}

(The above compile script basically loops through some of my OpenAPI files, and uses fs to write new files to /dist with variables and types inferred from the OpenAPI specs.)

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "esModuleInterop": true,
    "noEmit": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "noImplicitAny": true,
    // Allow for newer ES6 JS syntax (eg Set, array.find, etc)
    "target": "es6",
    "lib": [
      // Allow for newer syntax and other variables/tools
      "es6",
      // Object.entries and Object.values
      "es2017.object",
      // Window, etc
      "dom",
      // array.includes
      "es2016.array.include",
      // Promises, Async/Await
      "es2018"
    ]
  },
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  }
}

dist/example.ts

module.exports.defaultExample = {
  title: 'whatever',
  name: 'Whatever'
};

dist/example.d.ts

export interface Document {
  title: string;
  name: string;
  size?: number;
  mimeType?: string;
  data?: string;
}
export declare const defaultExample: Document;
6
  • 1
    "TS library that involves parsing TS code, generating types and additional variables from it in a complex process, and spitting out a set of files" - is that your build step, or is your library supposed to be used as a build step in the user's code?
    – Bergi
    Jun 14, 2022 at 21:15
  • That's my build step. sorry will clarify above
    – Sasha
    Jun 14, 2022 at 22:48
  • In that case, you should be able to spit out regular .ts files, and then transpile them as usual for distribution (that's just the first article I found, there might be better ones)
    – Bergi
    Jun 14, 2022 at 22:52
  • 1
    Regarding "error when I tried to run the specs, because Jest doesn't babel-process node_modules by default" - is that running tests of your library, or running tests in an application that uses your library?
    – Bergi
    Jun 14, 2022 at 22:55
  • 1
    Why don't you generate TypeScript code from the OpenAPI specs, and then compile that TypeScript code using tsc (or something similar standard)? Perhaps with a dynamic compile script, that makes one tsc call per api folder or whatever you need.
    – Bergi
    Jun 15, 2022 at 0:28

1 Answer 1

0

I figured out a solution that worked for me at least, by following @Bergi's advice above to use tsc, (tsc --outDir -d dist someFile.ts) to output declarations and JS files, which I could then copy the basic structure of.

Rather than share my super-specific and lengthy compilation code, I think it'd be more useful to just show how things ended up exported. The basic structure was parallel JS files, which followed a exports export syntax, and d.ts files which exported the types (both verbatim matches to JS vars and additional types):

- index.js
- index.d.ts
- folder
 |- something.js
 |- something.d.ts

All compiled .js files had the following at the top of them:

"use strict";
exports.__esModule = true;

And then exported things either as exports.[varName] or exports.default. They also imported other modules using the const defaultExample = require("./examples/default").default; syntax (or const something = require("./examples/whatever").something;). As in

const defaultExample = require("./examples/default").default;
"use strict";
exports.__esModule = true;

exports.someArray = ["one", "two", "three"];
exports.defaultExample = defaultExample;

The accompanying .d.ts file then looked like this:

export declare interface ExampleInterface {
// ...
}

export declare const defaultExample: ExampleInterface;
export declare const someArray: string[];
// etc

This format of export works correctly in the consuming app. Variables (eg defaultExample) are available, and types are introspected on hover etc. They work smoothly with the specs as well. Weird hacky solution, as generally a library of some sort will do the official compilation, but at least I find it helpful to know how TS modules are simply structured for functional import.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.