Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 22 additions & 14 deletions packages/core/src/transform/template/rewrite-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,27 @@ import { calculateCompanionTemplateSpans } from './inlining/companion-file.js';
*/
export type RewriteInput = { script: SourceFile; template?: SourceFile };

// HACK: We prefix every transformed TS file with these non-existent imports
// because it causes TypeScript to consider `.gts` and `.gjs` as possible
// implied extensions when extensions are omitted from import module specifiers,
// i.e. it causes `import FooComponent from './foo';` to work given a `foo.gts` file.
//
// Origin of this hack:
// https://github.com/typed-ember/glint/issues/806#issuecomment-2758616327
//
// This approach has the following desirable properties:
//
// 1. It doesn't break Organize Imports command
// 2. It doesn't introduce any keywords/variables that'll show up in auto-complete suggestions
const EXTENSION_FIXING_HEADER_HACK = `
// @ts-expect-error
({} as typeof import('./__glint-hacky-nonexistent.gts'));

// @ts-expect-error
({} as typeof import('./__glint-hacky-nonexistent.gjs'));

`;

/**
* Given the script and/or template that together comprise a component module,
* returns a `TransformedModule` representing the combined result, with the
Expand Down Expand Up @@ -68,25 +89,12 @@ function calculateCorrelatedSpans(
let directives: Array<Directive> = [];
let errors: Array<TransformError> = [];
let partialSpans: Array<PartialCorrelatedSpan> = [
// HACK: We prefix every transformed TS file with these non-existent imports
// because it causes TypeScript to consider `.gts` and `.gjs` as possible
// implied extensions when extensions are omitted from import module specifiers,
// i.e. it causes `import FooComponent from './foo';` to work given a `foo.gts` file.
//
// Origin of this hack:
// https://github.com/typed-ember/glint/issues/806#issuecomment-2758616327
//
// Note that these imports WILL generate diagnostic errors, but because they're
// mapped to zero-length source code spans, they're essentially mapped to nothing,
// and when Volar reverse-transforms the diagnostics back to the original source
// code, they'll be discarded.
{
originalFile: script,
originalStart: 0,
originalLength: 0,
insertionPoint: 0,
transformedSource:
"import __GLINT_GTS_EXTENSION_HACK__ from './__glint-non-existent.gts';\n import __GLINT_GJS_EXTENSION_HACK__ from './__glint-non-existent.gjs';\n",
transformedSource: EXTENSION_FIXING_HEADER_HACK,
},
];

Expand Down
Loading
Loading