react μ€ν°λμμ 리μ‘νΈλ₯Ό λ€λ£¨λ κΈ°μ μ΄λΌλ μ± μ μ μ νκ³ μ΄ μ± μ μ½κ³ λ°°μ΄ κ²μ λ°νμΌλ‘ μμ±λμλ€.
main
)λ‘ ν©μ Έμ§λ€.main
νμΌ ν¬κΈ°λ 컀μ§λλ° κ·Έλ¬λ©΄ νμ΄μ§ λ‘λ© μ μ§κΈ λΉμ₯ νμνμ§ μμ μ½λλ μ λΆ λΆλ¬μ νμ΄μ§ λ‘λ© μκ°μ΄ κΈΈμ΄μ Έ μ¬μ©μ κ²½νλ μ μ’μμ§κ³ νΈλν½λ μ¦κ°νλ€.code spliting
μ μ μ©νλ©΄ λΉμ₯ νμνμ§ μμ μ½λλ λΆλ¦¬μμΌ λμ€μ νμν λ λΆλ¬μμ μ¬μ©ν μ μλ€. (μ½λ λΉλκΈ° λ‘λ©) => νμ΄μ§ λ‘λ© μκ°μ΄ κ°μ λλ€.// notify.js
export default function notify(){
alert("μλ
νμΈμ!");
}
// App.js
// import notify from "./notify";
function App(){
const onClick = () => {
import("./notify").then(result => result.default());
// notify();
}
return (
<button onClick={onClick}>Notify</button>
);
}
import
λ₯Ό ν΅ν΄ nofity
λ₯Ό λΆλ¬μ€λ©΄ notify
μ½λκ° main
νμΌ μμ λ€μ΄κ°κ² λλ€.import()
ꡬ문μ μ¬μ©νλ©΄ μ½λλ₯Ό νμν μμ μ λΆλ¬μ μ¬μ©ν μ μκ³ μ½λλ λ°λ‘ νμΌμ λΆλ¦¬μμΌ μ μ₯λλ€.chunk
νμΌ: μ½λ μ€ν리ν
μ μμ±λλ μλ°μ€ν¬λ¦½νΈ νμΌimport()
ꡬ문μ νλ‘λ―Έμ€ κ°μ²΄λ₯Ό λ°ννλλ° νλ‘λ―Έμ€ κ°μ²΄μ λ°νκ°μ λΆλ¬μ¨ λͺ¨λμ΄λ€.import()
λ₯Ό ν΅ν΄ μ»΄ν¬λνΈλ₯Ό νμν μμ μ λΆλ¬μ μ»΄ν¬λνΈ μ체λ₯Ό state
μ λ£λλ€.// SplitMe.js
const SplitMe = () => {
return <div>SplitMe</div>;
}
export default SplitMe;
// App.js
import { Component } from "react";
class App extends Component{
state = {
SplitMe: null
};
handleClick = async () => {
const loadingModule = await import("./SplitMe");
this.setState({
SplitMe: loadingModule.default
});
}
render() {
const { SplitMe } = this.state;
return (
<div>
<button onClick={handleClick}>Click!</button>
{SplitMe && <SplitMe/>
</div>
);
}
}
React.lazy()
import()
ꡬ문μ λ°ννλ μ½λ°±ν¨μλ₯Ό μΈμλ‘ κ°λλ€.import()
ꡬ문μΌλ‘ λΆλ¬μμ§λ λͺ¨λμ React Component
λ₯Ό ν¬ν¨νλ©° default export
λ₯Ό κ°μ ΈμΌ νλ€.const SplitMe = React.lazy(() => import("./SplitMe"));
Suspense
React.lazy
λ‘ λΆλ¬μ¨ μ»΄ν¬λνΈλ Suspense
μ»΄ν¬λνΈ νμμμ λ λλ§λμ΄μΌ νλ€.fallback prop
λ‘ μ»΄ν¬λνΈκ° λ‘λλκΈΈ κΈ°λ€λ¦¬λ λμ λ λλ§νλ €λ React element
λ₯Ό μ€μ ν μ μλ€.// App.js
import { useState, Suspense } from "react";
const SplitMe = React.lazy(() => import("./SplitMe"));
function App(){
const [visible, setVisible] = useState(false);
const onClick = () => {
setVisible(true);
};
return (
<div>
<button onClick={handleClick}>Click!</button>
<SusPense fallback={<div>loading...</div>}>
{visible && <SplitMe/>}
</Suspense>
</div>
);
}
@loadable/component
λ μ½λ μ€ν리ν
μ νΈνκ² νλλ‘ λμμ£Όλ μλνν° λΌμ΄λΈλ¬λ¦¬μ΄λ€. const SplitMe = loadable(() => import("./SplitMe"), {
fallback: <div>loading...</div>
});
SplitMe.preload(); // 미리 λΆλ¬μ€κΈ°
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import loadable from "@loadable/component";
const Home = loadable(() => import('./routes/Home'));
const About = loadable(() => import('./routes/About'));
const App = () => (
<Router>
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/about" element={<About/>}/>
</Routes>
</Suspense>
</Router>
);
SPA
λ₯Ό κ°λ°νλ€κ³ νμ λ μ½λ μ€ν리ν
μ μ μ©νμ§ μμΌλ©΄ μλ°μ€ν¬λ¦½νΈ main
νμΌμ΄ 컀μ§κ² λλ€.