GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Rewrite relative import extensions with flag by andrewbranch · Pull Request #59767 · microsoft/TypeScript

Conversation

@andrewbranch

@andrewbranch Andrew Branch (andrewbranch) commented Aug 26, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Member

This PR adds --rewriteRelativeImportExtensions to support transforming module specifiers from e.g. "./utils.ts" to "./utils.js". A module specifier will be statically rewritten or shimmed during JS emit if it meets all of these criteria:

  • it begins with ./ or ../
  • it does not end in a declaration file name (.d.ts, .d.mts, .d.cts, .d.*.ts)
  • it ends in .ts, .tsx, .mts, or .cts

Error checking

Errors are issued in an attempt to catch common mistakes:

  • A module specifier will get rewritten but will break after rewriting:
    • "./foo.ts" actually resolves to ./foo.ts.ts or foo.ts/index.ts
    • "../other-project/src/index.ts" belongs to another project where outputs go to a different outDir
  • A module specifier will not get rewritten but will break after emitting as-is:
    • "#blah/foo.ts" resolves to foo.ts where the .ts matches through a wildcard

Syntax support

Scenario Example input Operation Example output
Import declarations import "./foo.ts" Rewrite import "./foo.js", require("./foo.js")
Export declarations export * from "./foo.ts" Rewrite export * from "./foo.js"
Import equals import foo = require("./foo.ts") Rewrite import foo = require("./foo.js")
Import calls with qualifying literal argument import("./foo.ts") Rewrite import("./foo.js")
Require calls in JS with qualifying literal argument require("./foo.ts") Rewrite require("./foo.js")
Import calls with non-literal argument import(getPath()) Shim import(__rewriteRelativeImportExtension(getPath()))
Require calls in JS with non-literal argument require(getPath()) Shim require(__rewriteRelativeImportExtension(getPath()))
Import calls with non-qualifying literal argument import("foo") None import("foo")
Require calls with non-qualifying literal argument require("foo") None require("foo")
Require calls in TS require("./foo.ts") None require("./foo.ts")
Indirected require calls (require)("./foo.ts") None (require)("./foo.ts")

Limitations and future work

This PR doesn’t change how module resolution works, so it’s still possible to reference a .ts file by a .js module specifier:

// @Filename: a.ts
export {};

// @Filename: b.ts
import {} from "./a.js"; // Always ok

We discussed that it’s probably desirable to turn this functionality off under --rewriteRelativeImportExtensions (and --allowImportingTsExtensions), since these options are a strong indicator that the user is going to run the input TS files in a TS-native runtime like Bun or node --experimental-strip-types. That would be a breaking change and isn’t included in this PR.

tslib PR: microsoft/tslib#270
Fixes #59597

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

NatoBoram, unional, xiaoxiangmoe, mkrause, kirillgroshkov, yinhangfeng, RobertAKARobin, clooney3, octet-stream, and sant123 reacted with thumbs up emoji JakobJingleheimer, niieani, kravetsone, Utwo, marvinhagemeister, ghoullier, brc-dd, zyhou, VladSez, souporserious, and 40 more reacted with hooray emoji tonivj5, marco-ippolito, JakobJingleheimer, karlhorky, Akiyamka, mitschabaude, niieani, kravetsone, Utwo, marvinhagemeister, and 37 more reacted with heart emoji jaydenseric reacted with eyes emoji
All reactions
  • 👍 10 reactions
  • 🎉 50 reactions
  • ❤️ 47 reactions
  • 👀 1 reaction
@typescript-bot TypeScript Bot (typescript-bot) assigned Andrew Branch (andrewbranch) Aug 26, 2024
@typescript-bot TypeScript Bot (typescript-bot) added Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug labels Aug 26, 2024
@andrewbranch

Andrew Branch (andrewbranch) commented Aug 26, 2024

Copy link
Copy Markdown
Member Author

TypeScript Bot (@typescript-bot) pack this

typescript-bot reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@typescript-bot

TypeScript Bot (typescript-bot) commented Aug 26, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Starting jobs; this comment will be updated as builds start and complete.

Command Status Results
pack this ✅ Started ✅ Results
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@typescript-bot

TypeScript Bot (typescript-bot) commented Aug 26, 2024 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

Hey Andrew Branch (@andrewbranch), I've packed this into an installable tgz. You can install it for testing by referencing it in your package.json like so:

{
    "devDependencies": {
        "typescript": "https://typescript.visualstudio.com/cf7ac146-d525-443c-b23c-0d58337efebc/_apis/build/builds/163457/artifacts?artifactName=tgz&fileId=2225118E5057943A4B80A3A9D8FE2EA5696226BA40FE09011C7C2241BF80844302&fileName=/typescript-5.7.0-insiders.20240826.tgz"
    }
}

and then running npm install.


There is also a playground for this build and an npm module you can use via "typescript": "npm:@typescript-deploys/[email protected]".;

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@DanielRosenwasser Daniel Rosenwasser (DanielRosenwasser) mentioned this pull request Aug 27, 2024
Design Meeting Notes, 8/27/2024 #59778
Closed
@andrewbranch Andrew Branch (andrewbranch) mentioned this pull request Sep 3, 2024
meeting 2024-08-28 nodejs/typescript#7
Merged
Andrew Branch (andrewbranch) added 2 commits September 6, 2024 15:05
@andrewbranch
Rewrite relative import extensions with flag
2439577
@andrewbranch
Add error for unsafe CJS-style resolution
2b06e62
@andrewbranch
Andrew Branch (andrewbranch) force-pushed the rewrite-extensions branch from 7159132 to 2b06e62 Compare September 6, 2024 22:50
@DanielRosenwasser Daniel Rosenwasser (DanielRosenwasser) mentioned this pull request Sep 9, 2024
TypeScript 5.7 Iteration Plan #59905
Closed
@typescript-bot

TypeScript Bot (typescript-bot) commented Sep 10, 2024

Copy link
Copy Markdown
Contributor

Looks like you're introducing a change to the public API surface area. If this includes breaking changes, please document them on our wiki's API Breaking Changes page.

Also, please make sure Daniel Rosenwasser (@DanielRosenwasser) and Ryan Cavanaugh (@RyanCavanaugh) are aware of the changes, just as a heads up.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@andrewbranch
Update baselines
a398ad1
@andrewbranch
Andrew Branch (andrewbranch) force-pushed the rewrite-extensions branch from bf25d52 to a398ad1 Compare September 10, 2024 16:42
Andrew Branch (andrewbranch) added 7 commits September 10, 2024 11:21
@andrewbranch
Add error for using .ts in non-rewritable paths
921f9ae
@andrewbranch
Silence error for referencing TS file in node_modules
ac8a2fa
@andrewbranch
Fix CJS error message interpolation
6e62350
@andrewbranch
Update baseline
c8ba95d
@andrewbranch
Use sourceFileMayBeEmitted
fce0a2d
@andrewbranch
Merge branch 'main' into rewrite-extensions
1558c7f
@andrewbranch
Add error for referencing referenced project input file
0d95ce2
@andrewbranch
Andrew Branch (andrewbranch) force-pushed the rewrite-extensions branch from ef2101a to 0d95ce2 Compare September 11, 2024 00:15
@andrewbranch
Add test with different but parallel rootDir/outDir
b88dddc
@mitschabaude Gregor Mitscha-Baude (mitschabaude) mentioned this pull request Sep 11, 2024
Import specifiers in --experimental-strip-types nodejs/loaders#214
Closed
@andrewbranch
Test all import/export declaration forms for emit
4867001
@andrewbranch Andrew Branch (andrewbranch) changed the title [experiment] Rewrite relative import extensions with flag Rewrite relative import extensions with flag Sep 11, 2024
@andrewbranch
Move transformations to module, rewrite dynamic import
62dab48
@microsoft Microsoft (microsoft) deleted a comment from TypeScript Bot (typescript-bot) Sep 17, 2024
@andrewbranch
Merge branch 'main' into rewrite-extensions
d87beef
@fan-zhang-sv Felix Zhang (fan-zhang-sv) mentioned this pull request Oct 7, 2024
fix: project module resolution coinbase/coinbase-wallet-sdk#1421
Closed
@NatoBoram Nato Boram (NatoBoram) mentioned this pull request Oct 10, 2024
🔧 rewriteRelativeImportExtensions NatoBoram/gigachad.ts#76
Merged
@andrewbranch
Andrew Branch (andrewbranch) deleted the rewrite-extensions branch October 14, 2024 15:13
@dominykas Dominykas Blyžė (dominykas) mentioned this pull request Oct 16, 2024
Ignore new TypeScript global leak hapijs/lab#1078
Merged
@DanielRosenwasser Daniel Rosenwasser (DanielRosenwasser) mentioned this pull request Oct 18, 2024
Design Meeting Notes, 9/17/2024 #60283
Closed
@nicolo-ribaudo

Nicolò Ribaudo (nicolo-ribaudo) commented Oct 23, 2024

Copy link
Copy Markdown
Contributor

Hey, I was reading the table in the PR description and I'm getting confused by these two lines:

Scenario Example input Operation Example output
Require calls in JS with qualifying literal argument require("./foo.ts") Rewrite require("./foo.js")
Require calls in TS require("./foo.ts") None require("./foo.ts")

Does it mean that require("./foo.ts") will be rewritten if it's inside a JS file, but not if it's inside a TS file?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@andrewbranch

Andrew Branch (andrewbranch) commented Oct 23, 2024

Copy link
Copy Markdown
Member Author

Yes. Plain require calls aren’t recognized as special in TS files. You’ll notice in JS that require("./foo") performs module resolution (the compiler knows the type to return), but in TS, require isn’t even allowed unless it’s declared as a global function, in which case that function’s return type is used (usually any).

nicolo-ribaudo reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jamiebuilds Jamie Kyle (jamiebuilds) mentioned this pull request Nov 1, 2024
rewriteRelativeImportExtensions and resolveJsonModule #60392
Closed
@fpapado Fotis Papadogeorgopoulos (fpapado) mentioned this pull request Nov 3, 2024
The error for allowImportingTsExtensions does not reference rewriteRelativeImportExtensions #60397
Closed
@mantou132 Xianqiao Wang (mantou132) mentioned this pull request Nov 11, 2024
Build to ESM: auto add .js extension mantou132/gem#103
Closed
Jack Williams (jpwilliams) added a commit to inngest/inngest-js that referenced this pull request Nov 25, 2024
@jpwilliams
Use .ts extensions instead of .js
7eb442f
See microsoft/TypeScript#59767
@jpwilliams Jack Williams (jpwilliams) mentioned this pull request Nov 25, 2024
Ensure support for typescript@~5.7.0 inngest/inngest-js#760
Merged
2 of 3 tasks
Jack Williams (jpwilliams) added a commit to inngest/inngest-js that referenced this pull request Nov 25, 2024
@jpwilliams
Ensure support for typescript@~5.7.0 (#760)
efc6c79
## Summary
<!-- Succinctly describe your change, providing context, what you've
changed, and why. -->

Ensures support for `typescript@~5.7.0` by adding a new PR check. See
[Announcing TypeScript 5.7 -
TypeScript](https://devblogs.microsoft.com/typescript/announcing-typescript-5-7/).

Ideally we would take advantage of the new
`rewriteRelativeImportExtensions` added in microsoft/TypeScript#59767
which would allow us to correctly import `.ts` extensions instead of
requiring `.js`, ready for better Deno/Bun support, as well as Node
support when running `.ts` files directly.

Unfortunately, `typescript<5.0.0` doesn't support the compiled output;
we'll have to wait for v4 to use that.

## Checklist
<!-- Tick these items off as you progress. -->
<!-- If an item isn't applicable, ideally please strikeout the item by
wrapping it in "~~"" and suffix it with "N/A My reason for skipping
this." -->
<!-- e.g. "- [ ] ~~Added tests~~ N/A Only touches docs" -->

- [ ] ~Added a [docs PR](https://github.com/inngest/website) that
references this PR~ N/A KTLO
- [x] Added unit/integration tests
- [x] Added changesets if applicable

## Related

- https://devblogs.microsoft.com/typescript/announcing-typescript-5-7/
- microsoft/TypeScript#59767
@jremy42

Jonathan R. (jremy42) commented Dec 2, 2024

Copy link
Copy Markdown

Just out of curiosity, I’m facing an issue where my .d.ts files don’t have an extension in the path. For example: export * as v1alpha2 from './v1alpha2/index.gen';. Why is the .ts extension mandatory to transform it into .js? Thank you.

philibea reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nyan-left

Deimantas Jakovlevas (nyan-left) commented Dec 6, 2024

Copy link
Copy Markdown

Ryan Cavanaugh (@RyanCavanaugh)

Imports in .d.ts files are allowed to use .ts extensions regardless of config, so I wouldn't really consider that a bug.

While .d.ts files may allow .ts extensions in imports without configuration, wouldn't this break backwards compatibility for libraries targeting TypeScript 4 support since allowImportingTsExtensions wasn't introduced until TypeScript 5?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nyan-left Deimantas Jakovlevas (nyan-left) mentioned this pull request Dec 6, 2024
[JavaScript] - "node" module resolution react/yoga#1760
Closed
1 task done
sant123
Santiago Aguilar Hernández (sant123) reviewed Jan 23, 2025
View reviewed changes
Comment thread src/compiler/factory/emitHelpers.ts
text: `
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
if (typeof path === "string" && /^\\.\\.?\\//.test(path)) {
return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {

@sant123 Santiago Aguilar Hernández (sant123) Jan 23, 2025

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If a path contains .jsx it is preserved even with the preserveJsx argument.

Should the regex be /\.([jt]sx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i?

This now works:

console.log(rewriteRelativeImportExtension("./main.tsx"));
console.log(rewriteRelativeImportExtension("./main.ts"));
console.log(rewriteRelativeImportExtension("./main.jsx"));
console.log(rewriteRelativeImportExtension("./main.jsx", true));
console.log(rewriteRelativeImportExtension("./main.js"));
./main.js
./main.js
./main.js
./main.jsx
./main.js

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@andrewbranch Andrew Branch (andrewbranch) Jan 23, 2025

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you clarify your actual behavior and expected behavior?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@sant123 Santiago Aguilar Hernández (sant123) Jan 23, 2025

Copy link
Copy Markdown

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nevermind, I'm writing a plugin that is based on __rewriteRelativeImportExtension. For Typescript is fine, however for esbuild the .jsx can the transformed to .js.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@MartinJohns Martin Johns (MartinJohns) mentioned this pull request Jan 24, 2025
rewriteRelativeImportExtensions: tsc doesn't rewrite extensions in emitted declaration files #61037
Open
@cefn Cefn Hoile (cefn) mentioned this pull request Jan 26, 2025
Add barrel export cefn/nextjs-typescript-monorepo#2
Merged
@JLHwung Huáng Jùnliàng (JLHwung) mentioned this pull request Feb 10, 2025
Fix: align behaviour to tsc rewriteRelativeImportExtensions babel/babel#17118
Merged
@CPunisher CPunisher mentioned this pull request Mar 2, 2025
[RFC] Progressively rewrite import specifiers swc-project/swc#10130
Closed
@nwidynski

Nikolas Schröter (nwidynski) commented Mar 23, 2025 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Andrew Branch (@andrewbranch) Ryan Cavanaugh (@RyanCavanaugh) Shouldn't calls to import.meta.resolve()/require.resolve() also be shimmed as part of this flag? The MDN docs suggest this should be the case.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@nwidynski Nikolas Schröter (nwidynski) mentioned this pull request Apr 6, 2025
import.meta.resolve is not shimmed when using --rewriteRelativeImportExtensions #61541
Closed
@andrewbranch Andrew Branch (andrewbranch) mentioned this pull request Jun 9, 2025
Port TypeScript PR #59767: Rewrite relative import extensions with flag microsoft/typescript-go#1113
Closed
This was referenced Jun 9, 2025
[WIP] Port TypeScript PR #59767: Rewrite relative import extensions with flag microsoft/typescript-go#1114
Closed
Port TypeScript PR #59767: Rewrite relative import extensions with flag microsoft/typescript-go#1138
Merged
@Tobbe Tobbe Lundberg (Tobbe) mentioned this pull request Aug 24, 2025
[TODO]: Add .js npm module test cedarjs/cedar#399
Open
@darksabrefr Clément Billoré (darksabrefr) mentioned this pull request Sep 17, 2025
Can't control which functional imports are shimmed under rewriteRelativeImportExtensions #62459
Closed
1 task done
@claude claude Bot mentioned this pull request Dec 18, 2025
fix(es/transforms): Update _ts_rewrite_relative_import_extension helper code swc-project/swc#11382
Merged
@microsoft Microsoft (microsoft) locked as resolved and limited conversation to collaborators Mar 9, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Reviewers

@weswigham Wesley Wigham (weswigham) weswigham left review comments
@jakebailey Jake Bailey (jakebailey) jakebailey approved these changes
@sheetalkamat Sheetal Nandi (sheetalkamat) Awaiting requested review from sheetalkamat
+2 more reviewers
@sant123 Santiago Aguilar Hernández (sant123) sant123 left review comments
@rbuckton Ron Buckton (rbuckton) rbuckton approved these changes
Reviewers whose approvals may not affect merge requirements

Uh oh!

There was an error while loading. Please reload this page.

Assignees

@andrewbranch Andrew Branch (andrewbranch)

Labels

Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Rewrite imports with ".ts" extension to ".js" to support Nodejs's "--experimental-strip-types"

Uh oh!

There was an error while loading. Please reload this page.

14 participants

@andrewbranch @typescript-bot @bakkot @jlmart88 @RyanCavanaugh @AlttiRi @nicolo-ribaudo @jremy42 @nyan-left @nwidynski @weswigham @rbuckton @jakebailey @sant123
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.