Skip to content

fix(compiler-sfc): simulate allowArbitraryExtensions on resolving type (fix #13295) #13301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 16, 2025

Conversation

Teages
Copy link
Contributor

@Teages Teages commented May 9, 2025

resolve #13295

Currently, Vue only analyzes types from known type sources such as .ts files and Vue SFCs (.vue files). This PR enables Vue to mimic TypeScript 5.0's allowArbitraryExtensions option behavior, allowing type imports from type definitions of unknown type sources (e.g., .css files).

Following TypeScript's documentation, when encountering files from unknown type sources, we will attempt to locate their type definitions in:

  • ./foo.vue: ./foo.d.vue.ts
  • ./bar.css: ./bar.d.css.ts

Link to minimal reproduction

https://github.com/Teages/vue-allow-arbitrary-extensions

Related issues

nuxt/module-builder#597
unjs/mkdist#270
unjs/mkdist#268 (comment)

microsoft/TypeScript#50133

Summary by CodeRabbit

  • New Features
    • Improved support for TypeScript's allowArbitraryExtensions feature, allowing type imports from files with unconventional extensions (e.g., .d.vue.ts, .d.css.ts).
  • Tests
    • Added test coverage for importing types from files with arbitrary extensions to ensure correct type resolution and runtime inference.

Copy link

coderabbitai bot commented May 9, 2025

Walkthrough

The changes introduce support for TypeScript's allowArbitraryExtensions option in the type resolver. The resolver now checks for and uses .d<ext>.ts declaration files when importing types from files with non-standard extensions. A new test verifies correct type resolution from .d.vue.ts and .d.css.ts files.

Changes

File(s) Change Summary
packages/compiler-sfc/src/script/resolveType.ts Updated file resolution logic to support .d<ext>.ts declaration files for arbitrary extensions; updated parseFile signature to accept fs argument; refined .vue.ts handling to exclude .d.vue.ts files from extension stripping.
packages/compiler-sfc/tests/compileScript/resolveType.spec.ts Added a test case to verify type resolution from files with arbitrary extensions and their corresponding declaration files.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Resolver
    participant FS

    User->>Resolver: Import type from './Foo.vue'
    Resolver->>FS: Check if './Foo.vue' exists
    alt Unknown extension and allowArbitraryExtensions enabled
        Resolver->>FS: Check if './Foo.d.vue.ts' exists
        alt Declaration file exists
            Resolver->>FS: Read './Foo.d.vue.ts'
            Resolver->>Resolver: Parse type from declaration file
        else Declaration file does not exist
            Resolver->>FS: Read './Foo.vue'
            Resolver->>Resolver: Parse type from original file
        end
    else Known extension
        Resolver->>FS: Read './Foo.vue'
        Resolver->>Resolver: Parse type from original file
    end
Loading

Assessment against linked issues

Objective Addressed Explanation
Support resolving types from .d<ext>.ts declaration files when allowArbitraryExtensions is enabled (#13295)
Ensure .vue.ts handling does not affect .d.vue.ts files (#13295)
Add tests to verify correct type resolution for arbitrary extensions (#13295)

Poem

In a warren of files with names so strange,
Now rabbits resolve types across each range.
From .vue to .css, with .d in the mix,
Arbitrary extensions—no longer a trick!
With paws on the keys and whiskers held high,
This bunny brings types from files that comply!
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/compiler-sfc/src/script/resolveType.ts (1)

1155-1168: allowArbitraryExtensions implementation – consider extra fallbacks

Great to see the stub lookup being implemented. A couple of edge-cases you may want to cover:

  1. If the importee (e.g. ./foo.css) itself does not exist but ./foo.d.css.ts does, resolveExt() will currently fail, because the resolution path never checks for .d.<ext>.ts.
    Either extend resolveExt() (preferred) or add a quick tryResolve(arbitraryTypeSource) before giving up.

  2. The call to

resolveParserPlugins('ts', parserPlugins, true)

forces the “declaration file” flag to true, even though files like foo.d.css.ts are not .d.ts in the classical sense. Passing the real declaration-ness, e.g.

/\.\d\.[cm]?ts$/.test(arbitraryTypeSource)

keeps behaviour consistent with the existing .d.ts branch.

Example tweak (inside resolveExt, but shown here for context):

-    tryResolve(filename + `.tsx`) ||
+    tryResolve(filename + `.tsx`) ||
+    // allowArbitraryExtensions support
+    (/\.[^./]+$/.test(filename) && tryResolve(`${filename}.d${extname(filename)}.ts`)) ||
     tryResolve(filename + `.d.ts`) ||

This would let consumers omit the physical .css/.svg file when they only care about types.

packages/compiler-sfc/__tests__/compileScript/resolveType.spec.ts (1)

1438-1459: Comprehensive test for allowArbitraryExtensions added – nice!

The new test covers both .vue and .css arbitrary-extension stubs and fails if runtime types are not inferred correctly — perfect regression protection.

For even stronger coverage, you might add a variant where the real resource (foo.vue / bar.css) is absent to ensure the suggested fallback path (see previous comment) still passes, but that’s optional.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f556c92 and fc9b3f6.

📒 Files selected for processing (2)
  • packages/compiler-sfc/__tests__/compileScript/resolveType.spec.ts (1 hunks)
  • packages/compiler-sfc/src/script/resolveType.ts (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (2)
packages/compiler-sfc/src/script/resolveType.ts (2)

861-872: Guard against mis-resolving .d.vue.ts – looks correct

The extra check !file.endsWith('.d.vue.ts') before stripping the trailing “.ts” prevents declaration stubs from being mapped back to the real .vue file by fileExists/readFile.
That behaviour was the root cause of #13295, so this condition is spot-on.
No further issues spotted here.


1129-1134: parseFile now requires fs: please verify all call-sites

parseFile’s signature has changed (parseFile(filename, source, fs, …)), and fileToScope was updated accordingly.
Please double-check (grep) that no other private helpers inside this module (or tests) still call the old 3-arg version — a silent compile-time break will only show up at runtime in non-TS builds.

@edison1105 edison1105 added ready to merge The PR is ready to be merged. scope: sfc 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. labels May 10, 2025
Copy link

github-actions bot commented May 10, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB 38.3 kB 34.5 kB
vue.global.prod.js 159 kB 58.4 kB 52 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.6 kB 18.2 kB 16.7 kB
createApp 54.5 kB 21.2 kB 19.4 kB
createSSRApp 58.7 kB 23 kB 20.9 kB
defineCustomElement 59.5 kB 22.8 kB 20.8 kB
overall 68.6 kB 26.4 kB 24.1 kB

Copy link

pkg-pr-new bot commented May 10, 2025

Open in StackBlitz

@vue/compiler-core

npm i https://pkg.pr.new/@vue/compiler-core@13301

@vue/compiler-dom

npm i https://pkg.pr.new/@vue/compiler-dom@13301

@vue/compiler-sfc

npm i https://pkg.pr.new/@vue/compiler-sfc@13301

@vue/compiler-ssr

npm i https://pkg.pr.new/@vue/compiler-ssr@13301

@vue/reactivity

npm i https://pkg.pr.new/@vue/reactivity@13301

@vue/runtime-core

npm i https://pkg.pr.new/@vue/runtime-core@13301

@vue/runtime-dom

npm i https://pkg.pr.new/@vue/runtime-dom@13301

@vue/server-renderer

npm i https://pkg.pr.new/@vue/server-renderer@13301

@vue/shared

npm i https://pkg.pr.new/@vue/shared@13301

vue

npm i https://pkg.pr.new/vue@13301

@vue/compat

npm i https://pkg.pr.new/@vue/compat@13301

commit: bedfcfe

@edison1105
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented May 16, 2025

📝 Ran ecosystem CI: Open

suite result latest scheduled
nuxt success success
language-tools success success
pinia success success
quasar success success
primevue success success
router success success
radix-vue success success
vue-macros success success
test-utils success success
vitepress success success
vue-i18n success ⏹️ cancelled
vant success success
vite-plugin-vue success success
vuetify success success
vueuse success success
vue-simple-compiler success success

@edison1105 edison1105 merged commit f7ce5ae into vuejs:main May 16, 2025
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. ready to merge The PR is ready to be merged. scope: sfc
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Compatible with tsconfig allowArbitraryExtensions option
4 participants