Why does Typescript compiler not change .ts to .js

2019-05-15 20:00发布

In the image below on the left in the folders you can see my /src Typescript (blue) compiled into my /dist (purple) Javascript using tsc.

enter image description here

You can see in the source file on the left that references a .ts module file that it isn't compiled into referencing a .js module file on the right.

Why not? How could the Javascript possibly run if tsc doesn't convert references?

Second question: I then tried manually changing the compiled reference from .ts to .js and running node dist/server.js but I get the error cannot find module tools/typescriptImport.js'. Why does node fail to find the module when it is correctly referenced (and you can see on the far right that it is a module)?

2条回答
够拽才男人
2楼-- · 2019-05-15 20:39

You are not supposed to write extension .ts in import commands.

Corresponding documentation: http://www.typescriptlang.org/Handbook#modules-going-external

查看更多
Animai°情兽
3楼-- · 2019-05-15 20:45

For starters, you have to remove the .ts extension from the import. TypeScript says that it treats it as a static string and won't change it.

Second, out of experience, I guess using a .d.ts file may solve your module not found error. I have solved many times by using this small hack. You can reference it using /// <reference path="tools/typeScriptImports.d.ts" />. Imagine .d.ts as the header file for TypeScript.

Lastly, try and make the path relative to the server.js file. So: ./tools/typeScriptImports.

查看更多
登录 后发表回答