Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tsc compile typescript which imports using file extension

I write my typescript code in an ecosystem-independent way. I decided to include file extensions in imports, matching the web and Deno.

import xyz from "./foo.ts";

How can I get the typescript compiler (tsc) to compile these files without the following error:

error TS2691: An import path cannot end with a '.ts' extension.

I am so far tried the following in my tsconfig.json to no avail:

{
    "compilerOptions": {
        "paths": {
            "*.js": ["*"],
            "*.ts": ["*"]
        },
        ...
    },
    ...
}
like image 873
David Callanan Avatar asked Apr 07 '26 05:04

David Callanan


1 Answers

You can compile without the errors by telling tsc to ignore all such import statements.

// @ts-ignore
import xyz from "./foo.ts";

To understand why you cannot config your way out of it, we have to dig into the underlying reasons of why TypeScript does not want you to use the .ts extension inside of import statement.

tsc does not rewrite the module filenames so if you give it

import xyz from "./foo.ts"

it does not produce a foo.js file, and the resulting compiled ECMAScript (of whatever version you specify) still says to import ./module.ts. Since the point of compiling to ECMAScript is to get rid of the TypeScript files, referencing a .ts file in the output is clearly not good.

What you want has been brought up in the TypeScript GitHub issues (see #27481, #11901). You may consider joining the discussion on GitHub.

like image 157
dwmorrin Avatar answered Apr 08 '26 21:04

dwmorrin