Skip to content

fix(compiler-sfc): throw mismatched script langs error before invoking babel #13194

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 2 commits into from
Aug 20, 2025

Conversation

adrianbrs
Copy link
Contributor

@adrianbrs adrianbrs commented Apr 13, 2025

Previously, babel would throw a misleading error if <script> and <script setup> used different lang values. Now, the compiler checks for language mismatch first and throws a clear error before invoking babel.

Close #13193

Before:
image

After:
image

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation for Vue SFCs: if <script> and <script setup> use different languages (e.g., lang="ts" vs lang="tsx"), compilation now fails early with a clear error: “<script> and <script setup> must have the same language type.”
  • Tests

    • Added test coverage to ensure mismatched language attributes between <script> and <script setup> are detected before parsing.

…g babel

Previously, babel would throw a misleading error if <script> and <script setup> used different lang values. Now, the compiler checks for language mismatch first and throws a clear error before invoking babel

Close vuejs#13193
Copy link

github-actions bot commented Apr 14, 2025

Size Report

Bundles

File Size Gzip Brotli
runtime-dom.global.prod.js 101 kB 38.4 kB 34.6 kB
vue.global.prod.js 159 kB 58.6 kB 52.2 kB

Usages

Name Size Gzip Brotli
createApp (CAPI only) 46.6 kB 18.2 kB 16.7 kB
createApp 54.6 kB 21.2 kB 19.4 kB
createSSRApp 58.8 kB 23 kB 20.9 kB
defineCustomElement 59.6 kB 22.8 kB 20.8 kB
overall 68.7 kB 26.4 kB 24.1 kB

Copy link

pkg-pr-new bot commented Apr 14, 2025

Open in StackBlitz

@vue/compiler-core

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

@vue/compiler-dom

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

@vue/compiler-sfc

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

@vue/compiler-ssr

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

@vue/reactivity

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

@vue/runtime-core

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

@vue/runtime-dom

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

@vue/server-renderer

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

@vue/shared

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

vue

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

@vue/compat

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

commit: 2f0a3a3

@edison1105 edison1105 added ready to merge The PR is ready to be merged. scope: compiler 🍰 p2-nice-to-have Priority 2: this is not breaking anything but nice to have it addressed. labels Apr 14, 2025
Copy link

coderabbitai bot commented Aug 20, 2025

Walkthrough

Adds an early language-mismatch validation between <script> and <script setup> in compileScript, throwing a specific error before Babel parsing. Updates unit tests to cover a ts/tsx mismatch case linked to issue #13193. No public API changes.

Changes

Cohort / File(s) Summary
Early mismatch validation in compiler
packages/compiler-sfc/src/compileScript.ts
Insert early check to compare lang of <script> and <script setup>; throw error on mismatch. Reorders context creation to occur after validation and removes later redundant check.
Unit tests for mismatch error
packages/compiler-sfc/__tests__/compileScript.spec.ts
Adds test asserting the specific error when <script lang="ts"> and <script setup lang="tsx"> coexist. References #13193.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor Dev
    participant SFC as SFCDescriptor
    participant CS as compileScript
    participant Ctx as ScriptCompileContext
    participant Parser as Babel/TS Parser

    Dev->>CS: compileScript(SFC, options)
    CS->>CS: Extract <script> & <script setup> langs
    note over CS: New: Early language mismatch check
    alt Languages differ
        CS-->>Dev: Throw Error("<script> and <script setup> must have the same language type.")
    else Languages match
        CS->>Ctx: Create ScriptCompileContext
        CS->>Parser: Parse/transform code
        Parser-->>CS: AST / transformed output
        CS-->>Dev: Compiled script result
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Assessment against linked issues

Objective Addressed Explanation
Emit specific error when <script> and <script setup> use different languages (#13193)

Assessment against linked issues: Out-of-scope changes

None found.

Suggested labels

scope: sfc, :hammer: p3-minor-bug

Suggested reviewers

  • Doctor-wu
  • LittleSound

Poem

In burrows where compilers hop and peep,
I nibbled bugs that woke from Babel’s sleep.
“TS or TSX?” I twitch my ear—
Now errors speak, all crisp and clear.
With tests to guard the carrot patch,
No mismatched langs will slip the hatch. 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@edison1105 edison1105 changed the title fix(compiler-sfc): throw mismatched script langs error before invoking babel (fix #13193) fix(compiler-sfc): throw mismatched script langs error before invoking babel Aug 20, 2025
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/compileScript.ts (1)

177-183: Normalize “no lang” to JS to avoid surprising breakages

As written, <script lang="js"> + <script setup> (no lang) will now be considered mismatched, even though “no lang” effectively means JS. That could be a subtle breaking change for users who explicitly set lang="js" on only one block.

Consider normalizing missing lang to 'js' for the comparison. This preserves the newly added behavior for real mismatches like ts vs tsx (and js vs jsx) while avoiding a strict mismatch for js vs implicit js.

Proposed minimal change:

-  if (script && scriptSetup && scriptLang !== scriptSetupLang) {
-    throw new Error(
-      `[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
-        `language type.`,
-    )
-  }
+  const normalizeLang = (l?: string) => (l == null ? 'js' : l)
+  if (
+    script &&
+    scriptSetup &&
+    normalizeLang(scriptLang) !== normalizeLang(scriptSetupLang)
+  ) {
+    throw new Error(
+      `[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
+        `language type.`,
+    )
+  }

Optional: enhance diagnostics by including the detected types:

-    throw new Error(
-      `[@vue/compiler-sfc] <script> and <script setup> must have the same ` +
-        `language type.`,
-    )
+    const a = normalizeLang(scriptLang)
+    const b = normalizeLang(scriptSetupLang)
+    throw new Error(
+      `[@vue/compiler-sfc] <script> and <script setup> must have the same language type. ` +
+      `Found "${a}" and "${b}".`
+    )
packages/compiler-sfc/__tests__/compileScript.spec.ts (1)

916-923: Add a couple more mismatch assertions to harden coverage

The new test covering ts vs tsx is great and directly proves the regression is fixed before Babel. Consider adding:

  • js vs jsx mismatch
  • Explicit lang="js" vs implicit JS (no lang) — only if you keep strict inequality. If you adopt normalization (treat missing as js), assert that this passes instead.

Here are two illustrative cases you can add under the same “errors” suite:

+  expect(() =>
+    compile(
+      `<script lang="js">foo()</script><script setup lang="jsx">bar()</script>`,
+    ),
+  ).toThrow(`<script> and <script setup> must have the same language type`)

If you adopt normalization (missing => js), then also assert no-throw for explicit js vs implicit js:

+  expect(() =>
+    compile(
+      `<script lang="js">foo()</script><script setup>bar()</script>`,
+    ),
+  ).not.toThrow()
📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1498821 and 2f0a3a3.

📒 Files selected for processing (2)
  • packages/compiler-sfc/__tests__/compileScript.spec.ts (1 hunks)
  • packages/compiler-sfc/src/compileScript.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/compiler-sfc/src/compileScript.ts (2)
packages/compiler-sfc/src/script/context.ts (1)
  • ScriptCompileContext (13-158)
packages/compiler-sfc/src/index.ts (1)
  • ScriptCompileContext (68-68)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test / e2e-test
🔇 Additional comments (3)
packages/compiler-sfc/src/compileScript.ts (2)

177-183: Early mismatch check prevents misleading Babel SyntaxError — solid fix

Catching the lang mismatch before initializing the parsing context is the right call and directly addresses #13193 by avoiding Babel’s misleading error. The error message is clear and scoped to compiler-sfc.


184-185: Creation of ScriptCompileContext after validation is in the right place

Moving new ScriptCompileContext(...) after the mismatch check ensures Babel parsing/plugins are never selected based on an incompatible lang. Good sequencing.

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

916-923: LGTM: regression covered with ts/tsx mismatch, and error text matches

The added assertion precisely covers #13193 and verifies the improved message surfaces before Babel parsing. Looks good.

@edison1105
Copy link
Member

/ecosystem-ci run

@vue-bot
Copy link
Contributor

vue-bot commented Aug 20, 2025

📝 Ran ecosystem CI: Open

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

@edison1105 edison1105 merged commit 0562548 into vuejs:main Aug 20, 2025
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🍰 p2-nice-to-have Priority 2: this is not breaking anything but nice to have it addressed. ready to merge The PR is ready to be merged. scope: compiler
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incorrect error message when <script> <script setup> has different languages
3 participants