Skip to content

Commit

Permalink
fix(es/react): Force refresh if code contains @refresh reset (#6749)
Browse files Browse the repository at this point in the history
  • Loading branch information
hyf0 committed Jan 4, 2023
1 parent 790c478 commit 36b26d3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
14 changes: 12 additions & 2 deletions crates/swc_ecma_transforms_react/src/refresh/mod.rs
Expand Up @@ -249,6 +249,12 @@ where
});
}

comments.with_leading(n.lo, |comments| {
if comments.iter().any(|c| c.text.contains("@refresh reset")) {
should_refresh = true
}
});

comments.with_trailing(n.lo, |comments| {
if comments.iter().any(|c| c.text.contains("@refresh reset")) {
should_refresh = true
Expand All @@ -265,14 +271,18 @@ impl<C: Comments> VisitMut for Refresh<C> {
// Does anyone write react without esmodule?
// fn visit_mut_script(&mut self, _: &mut Script) {}

fn visit_mut_module_items(&mut self, module_items: &mut Vec<ModuleItem>) {
fn visit_mut_module(&mut self, n: &mut Module) {
if !self.enable {
return;
}

// to collect comments
self.visit_module_items(module_items);
self.visit_module(n);

self.visit_mut_module_items(&mut n.body);
}

fn visit_mut_module_items(&mut self, module_items: &mut Vec<ModuleItem>) {
let used_in_jsx = collect_ident_in_jsx(module_items);

let mut items = Vec::with_capacity(module_items.len());
Expand Down
32 changes: 32 additions & 0 deletions crates/swc_ecma_transforms_react/src/refresh/tests.rs
Expand Up @@ -1535,3 +1535,35 @@ const a = (a)=>{
}
"#
);

test!(
::swc_ecma_parser::Syntax::Es(::swc_ecma_parser::EsConfig {
jsx: true,
..Default::default()
}),
tr,
issue_6022,
r#"/* @refresh reset */
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button type="button" onClick={() => setCount(c => c + 1)}>{count}</button>
);
}
"#,
r#"var _s = $RefreshSig$();
import { useState } from 'react';
function Counter() {
_s();
const [count, setCount] = useState(0);
return <button type="button" onClick={()=>setCount((c)=>c + 1)}>{count}</button>;
}
_s(Counter, "useState{[count, setCount](0)}", true);
_c = Counter;
var _c;
$RefreshReg$(_c, "Counter");
"#
);

0 comments on commit 36b26d3

Please sign in to comment.