How can I make ESLint force imports of .ts files to have a .js extension?

Viewed 519

I want to export ESM imports from my TypeScript project. TypeScript will not append file extensions, or convert .ts to .js, so I need to add .js to all of my imports manually. I can't figure out how to set up ESLint to require .js extensions for imports of .ts files. My project is too big to manually check if all the imports have .js at the end, so I need ESLint to check it for me. Does anyone know how to do this?

1 Answers

You can use the eslint-plugin-import plugin to force eslint errors for missing file extensions in import sources. Specifically, the "import/extensions" rule.

{
    "rules": {
        "import/extensions": [
            "error",
            "always"
        ]
    }
}

Edits

Specific extensions can be prohibited by assigning them a "never" value. For example, to exclude .ts extensions you could provide the following:

{
    "rules": {
        "import/extensions": [
            "error",
            "always",
            { "ts": "never" }
        ]
    }
}

Alternatively, if you want to prohibit all extensions except specific extensions (such as only allowing .js), you can provide the following: Nevermind, this doesn't work in all cases.

{
    "rules": {
        "import/extensions": [
            "error",
            "never",
            { "js": "always" }
        ]
    }
}
Related