How to run a ts script installed in node_modules with ts-node

Viewed 537

I have a package containing a script.ts file:

import path from 'path'
/* ... */
const loaded = require(path.resolve(process.cwd(), './src/dynamicPath/example.ts'))
// package.json
{
    "name": "mypackage",
    "bin": {
        "script": "./script.ts"
    }
}

It loads typescript files from the repo it's installed into. So I can't compile is and use node, I need to use ts-node

If I run ts-node script.ts, it works fine.

But when it's installed in ./node-modules/.bin/script.ts. If I run ts-node ./node-modules/.bin/scripts it doesn't work:

(node:25931) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
xxx/node_modules/.bin/script.ts:1
import path from 'path'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    ...

If I add type: module in mypackage's package.json then I have this error:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /__/node_modules/mypackage/script.ts
    at Loader.defaultGetFormat [as _getFormat] (internal/modules/esm/get_format.js:65:15)
    at Loader.getFormat (internal/modules/esm/loader.js:116:42)
    at Loader.getModuleJob (internal/modules/esm/loader.js:247:31)
    at async Loader.import (internal/modules/esm/loader.js:181:17)
    at async Object.loadESM (internal/process/esm_loader.js:68:5) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

How can I make the typescript script from node_modules works the same as the ones outside node_modules ?

A tsconfig.json of a repo where I install mypackage:

{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "lib": ["es2017"],
        "moduleResolution": "node",
        "outDir": "dist",
        "types": ["node"],
        "sourceMap": true
    },
    "include": ["src/**/*", "./node_modules/.bin/script", "./node_modules/mypackage/**"]
}

I'm trying to avoid using a postinstall npm script to copy the file in my sources.

1 Answers
  1. Make sure that you have "esModuleInterop": true in both tsconfigs - in mypackage and in dependent project where you are installing mypackage into.

  2. add #!ts-node on top of script.ts file

  3. no need to do ts-node ./node-modules/.bin/script do npx script instead (in directory of dependent project where you are installing mypackage)

Related