Skip to content
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

Experimental server optimization #54925

Merged
merged 9 commits into from
Sep 5, 2023
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
8 changes: 8 additions & 0 deletions packages/next-swc/crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ pub mod named_import_transform;
pub mod next_dynamic;
pub mod next_ssg;
pub mod optimize_barrel;
pub mod optimize_server_react;
pub mod page_config;
pub mod react_remove_properties;
pub mod react_server_components;
Expand Down Expand Up @@ -147,6 +148,9 @@ pub struct TransformOptions {

#[serde(default)]
pub cjs_require_optimizer: Option<cjs_optimizer::Config>,

#[serde(default)]
pub optimize_server_react: Option<optimize_server_react::Config>,
}

pub fn custom_before_pass<'a, C: Comments + 'a>(
Expand Down Expand Up @@ -265,6 +269,10 @@ where
Some(config) => Either::Left(optimize_barrel::optimize_barrel(config.clone())),
_ => Either::Right(noop()),
},
match &opts.optimize_server_react {
Some(config) => Either::Left(optimize_server_react::optimize_server_react(config.clone())),
_ => Either::Right(noop()),
},
opts.emotion
.as_ref()
.and_then(|config| {
Expand Down
194 changes: 194 additions & 0 deletions packages/next-swc/crates/core/src/optimize_server_react.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
// This transform optimizes React code for the server bundle, in particular:
// - Removes `useEffect` and `useLayoutEffect` calls
// - Refactors `useState` calls (under the `optimize_use_state` flag)

use serde::Deserialize;
use turbopack_binding::swc::core::{
common::DUMMY_SP,
ecma::{
ast::*,
visit::{Fold, FoldWith},
},
};

#[derive(Clone, Debug, Deserialize)]
pub struct Config {
pub optimize_use_state: bool,
}

pub fn optimize_server_react(config: Config) -> impl Fold {
OptimizeServerReact {
optimize_use_state: config.optimize_use_state,
..Default::default()
}
}

#[derive(Debug, Default)]
struct OptimizeServerReact {
optimize_use_state: bool,
react_ident: Option<Id>,
use_state_ident: Option<Id>,
use_effect_ident: Option<Id>,
use_layout_effect_ident: Option<Id>,
}

fn effect_has_side_effect_deps(call: &CallExpr) -> bool {
if call.args.len() != 2 {
return false;
}

// We can't optimize if the effect has a function call as a dependency:
// useEffect(() => {}, x())
if let box Expr::Call(_) = &call.args[1].expr {
return true;
}

// As well as:
// useEffect(() => {}, [x()])
if let box Expr::Array(arr) = &call.args[1].expr {
for elem in arr.elems.iter().flatten() {
if let ExprOrSpread {
expr: box Expr::Call(_),
..
} = elem
{
return true;
}
}
}

false
}

impl Fold for OptimizeServerReact {
fn fold_module_items(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> {
let mut new_items = vec![];

for item in items {
new_items.push(item.clone().fold_with(self));

if let ModuleItem::ModuleDecl(ModuleDecl::Import(import_decl)) = &item {
if import_decl.src.value.to_string() != "react" {
continue;
}
for specifier in &import_decl.specifiers {
if let ImportSpecifier::Named(named_import) = specifier {
let name = match &named_import.imported {
Some(n) => match &n {
ModuleExportName::Ident(n) => n.sym.to_string(),
ModuleExportName::Str(n) => n.value.to_string(),
},
None => named_import.local.sym.to_string(),
};

if name == "useState" {
self.use_state_ident = Some(named_import.local.to_id());
} else if name == "useEffect" {
self.use_effect_ident = Some(named_import.local.to_id());
} else if name == "useLayoutEffect" {
self.use_layout_effect_ident = Some(named_import.local.to_id());
}
} else if let ImportSpecifier::Default(default_import) = specifier {
self.react_ident = Some(default_import.local.to_id());
}
}
}
}

new_items
}

fn fold_expr(&mut self, expr: Expr) -> Expr {
if let Expr::Call(call) = &expr {
if let Callee::Expr(box Expr::Ident(f)) = &call.callee {
// Remove `useEffect` call
if let Some(use_effect_ident) = &self.use_effect_ident {
if &f.to_id() == use_effect_ident && !effect_has_side_effect_deps(call) {
return Expr::Lit(Lit::Null(Null { span: DUMMY_SP }));
}
}
// Remove `useLayoutEffect` call
if let Some(use_layout_effect_ident) = &self.use_layout_effect_ident {
if &f.to_id() == use_layout_effect_ident && !effect_has_side_effect_deps(call) {
return Expr::Lit(Lit::Null(Null { span: DUMMY_SP }));
}
}
} else if let Some(react_ident) = &self.react_ident {
if let Callee::Expr(box Expr::Member(member)) = &call.callee {
if let box Expr::Ident(f) = &member.obj {
if &f.to_id() == react_ident {
if let MemberProp::Ident(i) = &member.prop {
// Remove `React.useEffect` and `React.useLayoutEffect` calls
if i.sym.to_string() == "useEffect"
|| i.sym.to_string() == "useLayoutEffect"
{
return Expr::Lit(Lit::Null(Null { span: DUMMY_SP }));
}
}
}
}
}
}
}

expr
}

// const [state, setState] = useState(x);
// const [state, setState] = React.useState(x);
fn fold_var_declarators(&mut self, d: Vec<VarDeclarator>) -> Vec<VarDeclarator> {
if !self.optimize_use_state {
return d;
}

let mut new_d = vec![];
for decl in d {
if let Pat::Array(array_pat) = &decl.name {
if array_pat.elems.len() == 2 {
if let Some(array_pat_1) = &array_pat.elems[0] {
if let Some(array_pat_2) = &array_pat.elems[1] {
if let Some(box Expr::Call(call)) = &decl.init {
if let Callee::Expr(box Expr::Ident(f)) = &call.callee {
if let Some(use_state_ident) = &self.use_state_ident {
if &f.to_id() == use_state_ident && call.args.len() == 1 {
// const state = x, setState = () => {};
new_d.push(VarDeclarator {
definite: false,
name: array_pat_1.clone(),
init: Some(call.args[0].expr.clone()),
span: DUMMY_SP,
});
new_d.push(VarDeclarator {
definite: false,
name: array_pat_2.clone(),
init: Some(Box::new(Expr::Arrow(ArrowExpr {
body: Box::new(BlockStmtOrExpr::Expr(
Box::new(Expr::Lit(Lit::Null(Null {
span: DUMMY_SP,
}))),
)),
params: vec![],
is_async: false,
is_generator: false,
span: DUMMY_SP,
type_params: None,
return_type: None,
}))),
span: DUMMY_SP,
});
continue;
}
}
}
}
}
}
}
}

new_d.push(decl.fold_with(self));
}

new_d
}
}
23 changes: 23 additions & 0 deletions packages/next-swc/crates/core/tests/fixture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use next_swc::{
next_dynamic::next_dynamic,
next_ssg::next_ssg,
optimize_barrel::optimize_barrel,
optimize_server_react::optimize_server_react,
page_config::page_config_test,
react_remove_properties::remove_properties,
react_server_components::server_components,
Expand Down Expand Up @@ -580,6 +581,28 @@ fn optimize_barrel_wildcard_fixture(input: PathBuf) {
);
}

#[fixture("tests/fixture/optimize_server_react/**/input.js")]
fn optimize_server_react_fixture(input: PathBuf) {
let output = input.parent().unwrap().join("output.js");
test_fixture(
syntax(),
&|_tr| {
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

chain!(
resolver(unresolved_mark, top_level_mark, false),
optimize_server_react(next_swc::optimize_server_react::Config {
optimize_use_state: true
})
)
},
&input,
&output,
Default::default(),
);
}

fn json<T>(s: &str) -> T
where
T: DeserializeOwned,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { useEffect, useLayoutEffect, useMemo } from 'react'
import React from 'react'

export default function App() {
useEffect(() => {
console.log('Hello World')
}, [])

useLayoutEffect(() => {
function foo() {}
return () => {}
}, [1, 2, App])
shuding marked this conversation as resolved.
Show resolved Hide resolved

useLayoutEffect(() => {}, [runSideEffect()])
useEffect(() => {}, [1, runSideEffect(), 2])
useEffect(() => {}, getArray())

const a = useMemo(() => {
return 1
}, [])

React.useEffect(() => {
console.log('Hello World')
})

return (
<div>
<h1>Hello World</h1>
</div>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { useEffect, useLayoutEffect, useMemo } from 'react';
import React from 'react';
export default function App() {
null;
null;
useLayoutEffect(()=>{}, [
runSideEffect()
]);
useEffect(()=>{}, [
1,
runSideEffect(),
2
]);
useEffect(()=>{}, getArray());
const a = useMemo(()=>{
return 1;
}, []);
null;
return <div>

<h1>Hello World</h1>

</div>;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// https://github.com/vercel/commerce/blob/18167d22f31fce6c90f98912e514243236200989/components/layout/search/filter/dropdown.tsx#L16

'use client'

import { usePathname, useSearchParams } from 'next/navigation'
import { useEffect, useRef, useState } from 'react'

import { ChevronDownIcon } from '@heroicons/react/24/outline'
import { FilterItem } from './item'

export default function FilterItemDropdown({ list }) {
const pathname = usePathname()
const searchParams = useSearchParams()
const [active, setActive] = useState('')
const [openSelect, setOpenSelect] = useState(false)
const ref = useRef(null)

useEffect(() => {
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setOpenSelect(false)
}
}

window.addEventListener('click', handleClickOutside)
return () => window.removeEventListener('click', handleClickOutside)
}, [])

useEffect(() => {
list.forEach((listItem) => {
if (
('path' in listItem && pathname === listItem.path) ||
('slug' in listItem && searchParams.get('sort') === listItem.slug)
) {
setActive(listItem.title)
}
})
}, [pathname, list, searchParams])

return (
<div className="relative" ref={ref}>
<div
onClick={() => {
setOpenSelect(!openSelect)
}}
className="flex w-full items-center justify-between rounded border border-black/30 px-4 py-2 text-sm dark:border-white/30"
>
<div>{active}</div>
<ChevronDownIcon className="h-4" />
</div>
{openSelect && (
<div
onClick={() => {
setOpenSelect(false)
}}
className="absolute z-40 w-full rounded-b-md bg-white p-4 shadow-md dark:bg-black"
>
{list.map((item, i) => (
<FilterItem key={i} item={item} />
))}
</div>
)}
</div>
)
}
Loading