Skip to content

[Feature Request] Add compilerOption that validates ".js" extension is present in import path #52204

Closed
@alshdavid

Description

@alshdavid

Suggestion

Previously, the TypeScript team have made it clear that the compiler will not modify/rewrite import path extensions to convert TypeScript imports to valid ESModule imports - that's totally fine, this is not that discussion

Currently, the TypeScript compiler does accept import paths to TypeScript source files with .js extensions. Despite the import saying .js it will resolve the relevant .ts file:

import { foo } from "./foo.js"
// tsc will resolve "./foo.ts" but emit "./foo.js"

Can the TypeScript compiler include the capacity to enforce that extensions are present - (only a suggestion) perhaps via a new moduleResolution which respects the ES Module standard?

Perhaps:

{
  "compilerOptions": {
    "moduleResolution": "ESNext",
    "moduleExtension": ".js | .mjs", // currently only .js is supported
  }
}

Where, when enabled:

// File import
import { foo } from "./foo"    // Invalid - compiler throws
import { foo } from "./foo.js" // Valid

// Folder import
import { bar } from "./bar"          // Invalid - compiler throws
import { bar } from "./bar/index.js" // Valid

Pros:

  • This will help with the creation of JavaScript packages that can be used directly in the browser without a bundler

Cons:

  • Aforementioned libraries would need to ensure that all of their dependencies also included extensions

🔍 Search Terms

enforce typescript .js extension in import path

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

Labels

Needs InvestigationThis issue needs a team member to investigate its status.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions