TypeScript文件路径 .ts 在代码中,在编译时不正确。

huangapple go评论62阅读模式
英文:

Typescript file path .ts inside code, not correct when compiled

问题

I'm using the following code inside workers.ts, to load a Bull MQ worker file.

const worker = new Worker('parse', `${ __dirname }/workers/worker-parse.ts`);

Now during development I use the following script, which is working fine

npx pm2 start src/index.ts --watch

But when I build using tsc, the .ts file path won't work anymore since it's compiled to .js.

This is my production script

"prod": "tsc && npx pm2 start ecosystem.config.js --env production",

Now I'm wondering, is there any way that I can make sure that in the compiled version, my workers script will look for worker-parse.js, instead of .ts.

Or is there any way in TS to omit the extension? (Tried it but doesn't work out of the box)

英文:

I'm using the following code inside workers.ts, to load a Bull MQ worker file.

const worker = new Worker('parse', `${ __dirname }/workers/worker-parse.ts`);

Now during development I use the following script, which is working fine

npx pm2 start src/index.ts --watch

But when I build using tsc, the .ts file path won't work anymore since it's compiled to .js.

This is my production script

"prod": "tsc && npx pm2 start ecosystem.config.js --env production",

Now I'm wondering, is there any way that I can make sure that in the compiled version, my workers script will look for worker-parse.js, instead of .ts.

Or is there any way in TS to omit the extension? (Tried it but doesn't work out of the box)

答案1

得分: 1

  1. 尝试在typescript中使用worker-parse.js。在JS中,这显然是正确的。根据所使用的解析器(或运行时),这在TS中可能有效。例如,使用nodenext解析时,对于ts文件导入,需要使用.js扩展名,但不清楚对于您的确切情况是否适用于workers。

  2. import.meta.url(或__filename)获取当前文件的扩展名

const ext = import.meta.url.split('.').pop()!;
const worker = new Worker('parse', `${ __dirname }/workers/worker-parse.${ext}`);
英文:
  1. Try using worker-parse.js in typescript. In JS that would be obviously correct. Depending on the used resolver(or runtime) that could work in TS. E.g. with nodenext resolutions having .js extension for ts file imports is regiured, but no idea if that works with workers for your exact case.

  2. Get the extension of current file from import.meta.url (or __filename)

const ext = import.meta.url.split('.').pop()!;
const worker = new Worker('parse', `${ __dirname }/workers/worker-parse.${ext}`);

huangapple
  • 本文由 发表于 2023年6月22日 00:00:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定