1

I decided to use module and target ES2020, because it's time to catch up. I also like the idea of not using webpacking to compile the code to a single JS file. Anyway, I have the following code

//// main.ts:
import { Included } from "./Included";

export class Main {
    constructor() {
        console.log(`hi from main`);
        new Included().say();
    }
}
new Main();

/// included.ts:
export class Included {
    constructor() {
        console.log(`I was included!`);
    }
    say(){
        alert(`Wayasalikilikiyawangagat!`);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Using latest ts => js2018</title>
</head>
<body>
hi
<script type="module" src="./bin/main.js"></script>
</body>
</html>

It works fine in TypeScript, but when it compiles to ES2020 - it won't recognize

import { Included } from "./Included";

It wants only

import { Included } from "./Included.js";

But my Typescript does not add ".js" automatically. Here is my tsconfig:

{
    "compilerOptions": {
        "module": "ES2020",
        "target": "ES2020",
        "outDir": "./bin"
    },
    "include": [
        "src/**/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

Is it possible to make TS add ".js" on every import when it compiles files to JS? Thank you.

shal
  • 2,854
  • 4
  • 20
  • 31
  • Typescript is explicitly specified to never make any changes to module specifiers. Other tools may do so, but if typescript did so it would break the portability of code and conflict with higher-level build tools and web standards. Unfortunately, the browser loader specification is terrible and does not support anything like implicit or default extension resolution. You have to write .js in the typescript imports. – Aluan Haddad May 21 '21 at 00:25
  • One idea, you could make the serverside return the file without the JS extension, browsers don't require the .js extension either. Doing something like this in say Node.js / express would be very simple. – Keith May 21 '21 at 00:29
  • @Keith it's the same question but I don't think any of the answers are comprehensive. – Aluan Haddad May 21 '21 at 00:29
  • 1
    @Keith, in fact, I like your approach! Thanks – shal May 21 '21 at 00:54

0 Answers0