Typescript import are missing the .js extension when it compiled to javascript

Viewed 1386

I have decided to migrate my js project into ts, however I am faced with the following problem: all imports in ts files are missing the .js extension in the compiled js files. This in turn raises the following error: Loading failed for the module with source “http://localhost:5500/build/test/first”. on my browser console. Here is the code

/src/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script src="/build/test/last.js" type="module"></script>
</html>

/src/test/first.ts

export class First {
    name: string;

    constructor(name: string) {
        this.name = name
    }
}

/src/test/last.ts

import {First} from "./first"
class Last {

    constructor() {
        let name = new First("this is my name").name;
        console.log(name)
    }
}

new Last();

/build/test/first.js

export class First {
    constructor(name) {
        this.name = name;
    }
}

/build/test/last.js

import { First } from "./first";
class Last {
    constructor() {
        let name = new First("this is my name").name;
        console.log(name);
    }
}

Notice that in last.js, the import is missing a .js extension and if I manually add the missing extension every thing works as expected. And finally here is my ts config

{
    "compilerOptions": {
        "target": "ESNext",
        "lib": ["DOM","ES2017", "DOM.Iterable", "ScriptHost"],
        "watch": true,
        "rootDir": "./src", 
        "outDir": "./build",
        "sourceMap": true,
        "removeComments": true,
        "noEmitOnError": true,
        "strict": true,
    }
}

Is there something I am missing that is not adding the right extension on the imports? If so, please tell me what I am doing wrong. Thanks.

1 Answers

Is there something I am missing that is not adding the right extension on the imports?

Why would TypeScript randomly change your imports? You told it to import a module named ./first and it correctly compiled that to a an import for a module named ./first.

If you want to import a different module, you need to tell TypeScript to import a different module.

So, if you don't want to import a module named ./first but instead want to import a module named ./first.js, you need to tell TypeScript to import a module named ./first.js, not a module named ./first:

import {First} from "./first.js"
Related