Skip to content

ts-node path/file doesn't work in node 12.0.0 and node 12.1.0 #1565

Closed
@davidmurdoch

Description

Expected Behavior

ts-node docs, release notes, and tests all seem to claim support for Node >= v12, but that is not the case.

ts-node ./path/file should work, but it doesn't.

Actual Behavior

Cannot find module './'file
Require stack:

  • /home/david/work/ganache-core/path/imaginaryUncacheableRequireResolveScript

Steps to reproduce the problem and Minimal reproduction

create any TypeScript file at ./path/file.ts then run ts-node ./path/file

Specifications

ts-node v10.4.0
node v12.0.0
compiler v4.5.2
  • Operating system and version:

Kubuntu 20.04

The problem is that the requireResolveNonCached assumes all node 12s are the same, but node 12.0.0 and 12.1.0 seem to behave differently.

This seems to fix things for me:

/**
 * require.resolve an absolute path, tricking node into *not* caching the results.
 * Necessary so that we do not pollute require.resolve cache prior to installing require.extensions
 *
 * Is a terrible hack, because node does not expose the necessary cache invalidation APIs
 * https://stackoverflow.com/questions/59865584/how-to-invalidate-cached-require-resolve-results
 */
 function requireResolveNonCached(absoluteModuleSpecifier) {
    // node 12.0.0 and 12.1.0 fallback: The trick below triggers a node bug.
    // On those node versions, pollute the require cache instead. This is a deliberate
    // ts-node limitation that will *rarely* manifest, and will not matter once node 12
    // is end-of-life'd on 2022-04-30
    const [major, minor] = process.versions.node.split('.').map(v => parseInt(v, 10));
    const isSupportedNodeVersion = major >= 13 || (major == 12 && minor > 1);
    if (!isSupportedNodeVersion)
        return require.resolve(absoluteModuleSpecifier);
    const { dir, base } = (0, path_1.parse)(absoluteModuleSpecifier);
    const relativeModuleSpecifier = `./${base}`;
    const req = (0, util_2.createRequire)((0, path_1.join)(dir, 'imaginaryUncacheableRequireResolveScript'));
    return req.resolve(relativeModuleSpecifier, {
        paths: [
            `${guaranteedNonexistentDirectoryPrefix}${guaranteedNonexistentDirectorySuffix++}`,
            ...(req.resolve.paths(relativeModuleSpecifier) || []),
        ],
    });
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions