Skip to content

Detecting TypeScript support #2716

@B4nan

Description

@B4nan

🚀 Feature Proposal

When I run the tests with ts-jest preset, I am able to run/require TS files in the code. I would like to detect this fact on runtime, e.g. via environment variable like TS_JEST=true.

Motivation

I am author of MikroORM. It allows to discover entities either via references (entities: [User]) or via paths (entities: ['./entities']). To use the folder based discovery, I need to operate on the TS files when running via ts-node or ts-jest, as I am attaching some properties to the entity prototype and therefore need to work with TS file if that is what will be later used on runtime (in other words, if ts-node/ts-jest is used, I need to discover TS files from src, otherwise JS files from dist).

To deal with this, I have two different config options for entity paths, one for JS files, one for TS files. If I am able to detect typescript support (e.g. ts-node) I am using the TS one.

While there are several ways to detect if we are under ts-node environment (e.g. using !!process[Symbol.for('ts-node.register.instance')]), I failed to find one to detect if we are running via jest with ts-jest preset.

Example

Barebones example would be:

function discoverEntities(path: string) {
  const files = await globby(path);

  return files.map(path => {
    // for simplicity let's expect default export
    return require(path).default;
  })
}

if (process.env.TS_JEST) {
  const entities = discoverEntities('./src/entities/*.ts');
} else {
  const entities = discoverEntities('./dist/entities/*.js');
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions