-
-
Notifications
You must be signed in to change notification settings - Fork 34
perf: avoid babel in dev by using magic string for hook names injection #183
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
JoviDeCroock
merged 1 commit into
preactjs:main
from
sapphi-red:perf/avoid-babel-in-dev-by-using-magic-string-for-hook-names-injection
Feb 18, 2026
+180
−17
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| import { extractAssignedNames } from "@rollup/pluginutils"; | ||
| import type { Node, Program } from "estree"; | ||
| import MagicString from "magic-string"; | ||
| import type { Plugin } from "vite"; | ||
| import { walk } from "zimmerframe"; | ||
|
|
||
| import type { RollupFilter } from "./utils.js"; | ||
| import { parseId } from "./utils.js"; | ||
|
|
||
| const HOOK_IMPORTS = new Set(["preact/hooks", "preact/compat", "react"]); | ||
| const HOOK_NAME_RE = /^(useState|useReducer|useRef|useMemo)$/; | ||
| const FILTER_CODE_RE = /\buse(?:State|Reducer|Ref|Memo)\b/; | ||
|
|
||
| type NodeWithRange<N extends Node = Node> = N & { | ||
| start: number; | ||
| end: number; | ||
| }; | ||
|
|
||
| export interface TransformHookNamesPluginOptions { | ||
| devtoolsInProd?: boolean; | ||
| devToolsEnabled?: boolean; | ||
| shouldTransform: RollupFilter; | ||
| } | ||
|
|
||
| export function transformHookNamesPlugin({ | ||
| devtoolsInProd, | ||
| devToolsEnabled, | ||
| shouldTransform, | ||
| }: TransformHookNamesPluginOptions): Plugin { | ||
| return { | ||
| name: "preact:transform-hook-names", | ||
| configResolved(config) { | ||
| devToolsEnabled = | ||
| devToolsEnabled ?? (!config.isProduction || devtoolsInProd); | ||
| }, | ||
| transform(code, url) { | ||
| if (!devToolsEnabled) return; | ||
|
|
||
| const { id } = parseId(url); | ||
| if (!shouldTransform(id)) return; | ||
| if (!FILTER_CODE_RE.test(code)) return; | ||
|
|
||
| let ast: NodeWithRange<Program>; | ||
| try { | ||
| ast = this.parse(code) as NodeWithRange<Program>; | ||
| } catch { | ||
| return; | ||
| } | ||
|
|
||
| const importedHooks = getImportedHooks(ast); | ||
| if (importedHooks.size === 0) return; | ||
|
|
||
| const s = new MagicString(code); | ||
| let hasHelper = false; | ||
| walk<NodeWithRange, null>(ast, null, { | ||
| CallExpression(node, { path, next }) { | ||
| const callee = node.callee; | ||
| if (callee.type !== "Identifier") { | ||
| next(); | ||
| return; | ||
| } | ||
|
|
||
| const hookName = callee.name; | ||
| // the hook name might be shadowed by a local variable, | ||
| // but that false-positive is fine | ||
| // since `addHookName` is transparent | ||
| if (!HOOK_NAME_RE.test(hookName) || !importedHooks.has(hookName)) { | ||
| next(); | ||
| return; | ||
| } | ||
|
|
||
| const parent = path[path.length - 1]; | ||
| const bindingNames = getOuterBindingNames(parent); | ||
| if (bindingNames.length === 0) { | ||
| next(); | ||
| return; | ||
| } | ||
|
|
||
| let name = bindingNames[0]; | ||
| hasHelper = true; | ||
| s.prependLeft(node.start, "addHookName("); | ||
| s.appendRight(node.end, `, ${JSON.stringify(name)})`); | ||
| next(); | ||
| }, | ||
| }); | ||
| if (!hasHelper) return; | ||
|
|
||
| const firstNode = ast.body[0] as NodeWithRange; | ||
| s.prependLeft( | ||
| firstNode.start, | ||
| 'import { addHookName } from "preact/devtools";\n', | ||
| ); | ||
|
|
||
| return { | ||
| code: s.toString(), | ||
| map: s.generateMap({ hires: "boundary" }), | ||
| }; | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| function getImportedHooks(ast: NodeWithRange<Program>): Set<string> { | ||
| const hooks = new Set<string>(); | ||
| for (const node of ast.body) { | ||
| if (node.type !== "ImportDeclaration") continue; | ||
|
|
||
| const source = | ||
| typeof node.source.value === "string" ? node.source.value : null; | ||
| if (!source || !HOOK_IMPORTS.has(source)) continue; | ||
|
|
||
| for (const specifier of node.specifiers) { | ||
| if (specifier.type !== "ImportSpecifier") continue; | ||
|
|
||
| const importedName = specifier.imported.name; | ||
| if ( | ||
| !HOOK_NAME_RE.test(importedName) || | ||
| specifier.local.name !== importedName | ||
| ) | ||
| continue; | ||
|
|
||
| hooks.add(importedName); | ||
| } | ||
| } | ||
| return hooks; | ||
| } | ||
|
|
||
| function getOuterBindingNames(node: Node | undefined): string[] { | ||
| if (!node) return []; | ||
|
|
||
| switch (node.type) { | ||
| case "VariableDeclarator": | ||
| return extractAssignedNames(node.id); | ||
| case "AssignmentExpression": | ||
| return extractAssignedNames(node.left); | ||
| case "Identifier": | ||
| case "ArrayPattern": | ||
| case "ObjectPattern": | ||
| case "RestElement": | ||
| case "AssignmentPattern": | ||
| return extractAssignedNames(node); | ||
| default: | ||
| return []; | ||
| } | ||
| } |
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.
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.
Prefresh of line 300 will still be using Babel though 😅
Uh oh!
There was an error while loading. Please reload this page.
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.
Yes, it is. I meant the babel transform written directly in this plugin. The prefresh plugin currently runs a separate babel transform (parse + transform + codegen) pass, so this PR will remove half of the babel tranform pass.
In Vite 8, the react refresh transform can be handled by Oxc. So if we use that feature and port https://github.com/swc-project/plugins/tree/main/packages/prefresh and use magic-string for it similarly, we can remove babel completely.
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 you need any help with prefresh LMK, I'm actively working on the babel plugin for signals support atm