Skip to content

portability: allow .js in import specifiers #2066

Open
@trusktr

Description

@trusktr

It is awkward, but TypeScript officially supports using .js in import specifiers, like so:

import {foo} from './path/to/some/file.js'
console.log(foo)

where ./path/to/some/file.js does not actually exist, but the file ./path/to/some/file.ts actually exists, and TypeScript will correctly (officially) use file.ts.

In fact, to show how official it is, TypeScript more recently even added the feature that when you auto-import something, if you are already use .js extensions in all you import specifiers, the new automatically-added import statement will also have the .js extension for consistency.

But why?

When compiling TypeScript code to JavaScript, we want it to work out of the box in native ES Module systems (like in browsers).

TypeScript team has said they do not (currently at least) wish to modify import specifiers (f.e. converting .ts to .js), but that they officially support .js.

Thus, using the .js extensions makes importing in native ES Module systems easier, because browsers do not yet support things like import 'some/file': the browser will try to load the equivalent of 'current-file-folder/some/file' instead of 'current-file-folder/some/file.js' and it will fail, unless

  • the server is specifically configured to automatically find the matching file with the added extension, but this isn't default behavior in the average static non-js-specific file server.
  • one uses additional build tooling to insert the .js extensions after TypeScript compilation.

This feature would be compatible with TypeScript, and would allow us to compile to WebAssembly or to plain JavaScript with native ES Modules more easily without the extra workarounds.

Some people will despise the feature, but they don't have to use it. And honestly as an engineer that needs to get things done, it's a perfectly fine solution.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions