본문으로 건너뛰기

빌드와 배포 — dist/를 올리기

리액트 목차 만들고 배포하기 레슨 55 / 61

목차

레시피 보관함을 npm run build로 dist/ 폴더의 파일로 묶고, npm run preview로 그 파일을 배포 판으로 열어 보는 레슨입니다. /recipe-box/ 같은 하위 경로에 올릴 때는 vite.config.js의 base를 맞추고, VITE_로 시작하는 환경 변수는 코드가 읽으면 묶은 JS 안에 글로 들어가니 비밀 키를 넣지 않습니다.

이 단계 시작 파일은 고치기 · 정렬 · 통계 · 백업 레슨 예제의 파일 열넷입니다.

4단계 중 1단계. 1. 빌드. npm run build는 src/의 코드와 리액트를 묶어 dist/에 index.html · JS · CSS로 둡니다. 이름 가운데 글자는 파일 내용으로 정하는 해시이고, public/의 파일은 그대로 복사됩니다.

지금까지 레시피 보관함은 개발 서버(npm run dev)로 열었습니다. 개발 서버는 브라우저가 파일을 달라고 할 때마다 그 파일 하나를 바꿔 주고, 내 컴퓨터에서만 열립니다. 남에게 보이려면 파일을 미리 묶어 두고(빌드, build) 그 파일을 웹 서버에 올립니다(배포, deploy). 올릴 곳(GitHub Pages 같은 정적 호스팅 — 올린 파일을 그대로 내주는 곳)은 서비스마다 화면이 달라, 이 레슨은 올릴 dist/를 만들고 미리 보는 데까지 합니다. 어느 곳이든 올리는 것은 dist/ 안의 파일입니다.

1빌드 — npm run build가 만드는 dist/

개발 서버 터미널은 그대로 두고 새 터미널을 열어, recipe-box 폴더에서 npm run build를 칩니다. 끝 네 줄입니다.

터미널에 나온 줄
dist/index.html 0.46 kB │ gzip: 0.29 kB
dist/assets/index-nqMpL4T3.css 1.78 kB │ gzip: 0.81 kB
dist/assets/index-Cp5-6NZM.js 225.62 kB │ gzip: 70.84 kB
✓ built in 244ms

gzip: 뒤 수는 압축해 보낼 때의 크기이고, 크기와 시간은 판에 따라 조금 다를 수 있습니다. 프로젝트 폴더에 dist/가 생깁니다.

dist/ 안무엇
index.html브라우저가 처음 받는 쪽
assets/의 JSsrc/의 코드와 리액트를 묶은 한 파일
assets/의 CSSCSS를 묶은 한 파일
favicon.svg · icons.svgpublic/의 파일 그대로

여러 파일을 하나로 묶은 결과를 묶음(bundle)이라고 합니다. Vite 문서(Deploying a Static Site)는 'You may deploy this dist folder to any of your preferred platforms.'(이 dist 폴더를 원하는 곳에 올리면 된다)라고 적습니다.

이름의 Cp5-6NZM 같은 글자는 파일 내용으로 정하는 해시(hash)입니다. 고치지 않고 다시 빌드하면 이름이 같고, App.jsx의 제목 글만 고쳐 빌드하면 JS 이름만 바뀝니다.

dist/index.html의 script 줄은 /src/main.jsx 대신 /assets/index-Cp5-6NZM.js⁠를 부르고, CSS도 /assets/ 아래 파일을 부릅니다. 두 주소는 /로 시작해 사이트 뿌리부터 찾습니다.

맞혀 봅니다. 파일 탐색기(맥은 Finder)에서 dist/index.html을 크롬 창에 끌어다 놓아 파일로 열면(주소가 file://로 시작) 무엇이 보일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 레시피 보관함 화면
  • ② 하얀 화면
  • ③ 파일을 찾을 수 없다는 쪽
결과 보기

②입니다. 탭 제목은 recipe-box인데 화면은 하얗습니다. 콘솔의 빨간 줄은 Access to script at으로 시작하고, 가운데에 blocked by CORS policy(CORS 정책이 막음)가 있습니다. 같은 꼴의 CSS 줄과 net::ERR_FAILED로 끝나는 줄도 찍힙니다. 탭 그림 favicon.svg를 못 찾았다는 줄이 하나 더 찍히기도 합니다.

파일로 연 쪽은 묶은 JS를 받지 못합니다. 자바스크립트 과목에서 type="module"을 붙인 쪽을 더블클릭으로 열었을 때와 같은 막힘입니다(JS '웹 페이지에서 돌리기'). MDN 문서(Reason: CORS request not HTTP)는 'Many browsers, including Firefox and Chrome, now treat all local files as having opaque origins (by default).'라고 적습니다. 파일로 연 쪽이 다른 파일을 불러오면 CORS 오류가 나니, 테스트는 서버로 하라고 이어 적습니다. 주소를 ./assets/처럼 이 폴더 기준으로 바꿔 빌드해도 같은 빨간 줄과 하얀 화면입니다(주소 앞머리를 정하는 base는 3절).

예상과 다르면 그곳이 배울 곳입니다. ①을 골랐다면 index.html만 열리면 된다고 생각한 것입니다. 화면은 그 쪽이 부르는 JS가 그립니다. ③을 골랐다면 쪽 자체를 못 찾는다고 생각한 것입니다. index.html은 열리고, 막히는 것은 그 안이 부르는 JS · CSS입니다.

2배포 판 — npm run preview로 열기

빌드한 터미널에서 npm run preview를 치고, Local 줄의 주소 http://localhost:4173/⁠을 엽니다. 이렇게 연 쪽이 '순수한 컴포넌트' 레슨에서 본 배포 판입니다. 끌 때는 그 터미널에서 Ctrl+C를 누릅니다.

판명령 · 포트주는 파일
개발 판npm run dev · 5173src/를 그때그때 바꾼 것
배포 판npm run preview · 4173dist/ 그대로
배포한 사이트웹 서버 · 받은 주소dist/ 그대로

크롬에서 배포 판은 개발 판과 화면이 같고, 콘솔이 비어 있습니다. StrictMode가 한 번 더 부르지 않는 판입니다. Vite 문서(Deploying a Static Site)는 'It is important to note that vite preview is intended for previewing the build locally and not meant as a production server.'라고 적습니다. 남에게 보이는 사이트는 dist/를 받은 웹 서버가 줍니다.

3하위 경로 — base 맞추기

사이트 뿌리(/)가 아니라 /recipe-box/ 같은 폴더 주소 아래에 올리는 것을 하위 경로(subpath)에 올린다고 합니다. GitHub Pages의 저장소 주소(github.io 뒤에 저장소 이름이 붙는 꼴)가 하위 경로입니다.

base를 두지 않고 빌드한 dist/를 /recipe-box/ 아래에 올리면 화면이 하얗습니다. 빌드는 ✓ built in으로 끝나 오류가 없습니다. 개발 도구의 Network 판을 열고 쪽을 새로 고치면 단서가 보입니다.

브라우저가 달라고 한 주소받은 답
/recipe-box/200
/assets/index-Cp5-6NZM.js404
/assets/index-nqMpL4T3.css404
/favicon.svg404

콘솔에도 Failed to load resource⁠로 시작하는 빨간 줄이 찍힙니다. index.html은 왔지만, 그 안의 /assets/ 주소가 사이트 뿌리를 가리켜 /recipe-box/assets/의 파일을 찾지 못한 것입니다. vite.config.js에 base 한 줄을 더하고 다시 빌드합니다.

vite.config.js
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
  base: '/recipe-box/',
})

다시 빌드하면 dist/index.html 줄만 0.49 kB로 바뀌고, JS · CSS 이름은 그대로입니다. index.html이 부르는 주소가 /recipe-box/로 시작해 화면이 섭니다. Vite 문서(Deploying a Static Site)도 GitHub Pages 저장소 주소에는 base를 '/<REPO>/'(저장소 이름)로 두라고 적습니다.

4환경 변수 — VITE_ 값과 묶음

코드 밖에 두고 읽는 값을 환경 변수(environment variable)라고 합니다. Vite는 프로젝트 맨 위 폴더(package.json 옆)의 .env 파일에서 이름=값 줄을 읽고, 이름이 VITE_로 시작하는 것만 코드에 import.meta.env.이름으로 내줍니다. import.meta는 모듈 파일에 그 파일의 정보를 담아 주는 자바스크립트 문법이고, 그 안의 env는 Vite가 채웁니다.

직접 해 보는 차례는 맨 아래 '컴퓨터에서 해 보기' 4 · 5에 모았습니다(끝에 되돌림). .env에 VITE_TEST=찾아보기 한 줄을 두고 빌드해, 묶은 JS에서 찾아보기를 셉니다. 다음에는 그 값을 읽는 두 조각을 App.jsx에 넣고(첫 조각은 function App() 위, <p> 줄은 제목 줄 아래) 다시 빌드합니다.

src/App.jsx
// .env 의 VITE_TEST 값
const testText =
  import.meta.env.VITE_TEST;
src/App.jsx
        <h1>레시피 보관함</h1>
        <p>{testText}</p>

두 판의 묶은 JS에서 센 수입니다.

판찾아보기VITE_TEST
읽지 않음0곳0곳
읽음1곳0곳

코드가 읽지 않은 값은 묶음에 들어가지 않습니다. 읽으면 빌드가 그 자리에 값을 글로 써 넣고, 이름 VITE_TEST는 남기지 않습니다. 묶은 JS는 사이트를 여는 누구나 받는 파일이라, Vite 문서(Env Variables and Modes)는 'VITE_* variables should not contain sensitive information such as API keys.'라고 적습니다.

예제

끝 판은 앞 레슨 파일 열넷 그대로이고, 바뀐 파일은 3절의 vite.config.js 하나입니다. 파일 열넷과, 배포 판에서 '통계'를 누른 뒤 화면을 접어 둡니다.

src/ 파일 열넷과 배포 판 화면 보기 — 모두 앞 레슨 그대로

코드 주석의 번호는 틀마다 셉니다 — RecipesProvider.jsx의 2.는 'reducer로 모으기', useLocalStorage.js의 2. · 3.은 '커스텀 훅으로 빼기'의 걸음이고, 나머지 3. · 4. · 5.는 Thinking in React의 걸음입니다.

src/recipes.js — 앞 레슨 그대로입니다.

src/recipes.js
export const categories = [
  '한식',
  '양식',
  '일식',
  '중식',
  '디저트',
];

export const initialRecipes = [
  {
    id: 'r1',
    title: '김치볶음밥',
    category: '한식',
    minutes: 15,
    ingredients: [
      '밥',
      '김치',
      '달걀',
    ],
    favorite: true,
  },
  {
    id: 'r2',
    title: '토마토 파스타',
    category: '양식',
    minutes: 25,
    ingredients: [
      '파스타',
      '토마토',
    ],
    favorite: false,
  },
  {
    id: 'r3',
    title: '계란말이',
    category: '한식',
    minutes: 10,
    ingredients: [
      '달걀',
      '파',
    ],
    favorite: false,
  },
  {
    id: 'r4',
    title: '바나나 팬케이크',
    category: '디저트',
    minutes: 20,
    ingredients: [
      '바나나',
      '밀가루',
      '우유',
    ],
    favorite: true,
  },
];

src/recipesContexts.js — 앞 레슨 그대로입니다.

src/recipesContexts.js
import {
  createContext,
} from 'react';

export const RecipesContext =
  createContext(null);
export const
  RecipesDispatchContext =
    createContext(null);

src/RecipesProvider.jsx — 앞 레슨 그대로입니다.

src/RecipesProvider.jsx
import {
  useEffect,
  useReducer,
} from 'react';
import {
  initialRecipes,
} from './recipes.js';
import {
  RecipesContext,
  RecipesDispatchContext,
} from './recipesContexts.js';

const KEY =
  'recipe-box:recipes';

function loadRecipes() {
  const raw = localStorage
    .getItem(KEY);
  if (raw === null) {
    return initialRecipes;
  }
  return JSON.parse(raw);
}

function flipFavorite(recipe) {
  return {
    ...recipe,
    favorite: !recipe.favorite,
  };
}

function swapRecipe(
  recipes,
  next,
) {
  return recipes.map((r) =>
    r.id === next.id ? next : r,
  );
}

// 2. action마다 새 state
function recipesReducer(
  recipes,
  action,
) {
  switch (action.type) {
    case 'added':
      return [
        ...recipes,
        action.recipe,
      ];
    case 'updated':
      return swapRecipe(
        recipes,
        action.recipe,
      );
    case 'deleted':
      return recipes.filter(
        (r) =>
          r.id !== action.id,
      );
    case 'toggledFavorite':
      return recipes.map(
        (r) =>
          r.id === action.id
            ? flipFavorite(r)
            : r,
      );
    case 'replacedAll':
      return action.recipes;
    default:
      throw new Error(
        '모르는 action: ' +
          action.type,
      );
  }
}

function RecipesProvider({
  children,
}) {
  const [recipes, dispatch] =
    useReducer(
      recipesReducer,
      null,
      loadRecipes,
    );
  useEffect(() => {
    localStorage.setItem(
      KEY,
      JSON.stringify(recipes),
    );
  }, [recipes]);
  return (
    <RecipesContext
      value={recipes}
    >
      <RecipesDispatchContext
        value={dispatch}
      >
        {children}
      </RecipesDispatchContext>
    </RecipesContext>
  );
}

export default RecipesProvider;

src/useRecipes.js — 앞 레슨 그대로입니다.

src/useRecipes.js
import {
  useContext,
} from 'react';
import {
  RecipesContext,
  RecipesDispatchContext,
} from './recipesContexts.js';

export function useRecipes() {
  const recipes = useContext(
    RecipesContext,
  );
  if (recipes === null) {
    throw new Error(
      'useRecipes는 ' +
        'RecipesProvider ' +
        '안에서만 쓸 수 있습니다.',
    );
  }
  return recipes;
}

export function
  useRecipesDispatch() {
  const dispatch = useContext(
    RecipesDispatchContext,
  );
  if (dispatch === null) {
    throw new Error(
      'useRecipesDispatch는 ' +
        'RecipesProvider ' +
        '안에서만 쓸 수 있습니다.',
    );
  }
  return dispatch;
}

src/useLocalStorage.js — 앞 레슨 그대로입니다.

src/useLocalStorage.js
import {
  useEffect,
  useState,
} from 'react';

// 2. use로 시작하는 함수로 옮기기
function useLocalStorage(
  key,
  initial,
) {
  function load() {
    const raw = localStorage
      .getItem(key);
    const saved =
      JSON.parse(raw);
    return saved ?? initial;
  }
  const [value, setValue] =
    useState(load);
  useEffect(() => {
    localStorage.setItem(
      key,
      JSON.stringify(value),
    );
  }, [key, value]);
  // 3. 필요한 값만 돌려주기
  return [value, setValue];
}

export default useLocalStorage;

src/RecipeCard.jsx — 앞 레슨 그대로입니다.

src/RecipeCard.jsx
import {
  useRecipesDispatch,
} from './useRecipes.js';

function RecipeCard({
  recipe,
  onEdit,
}) {
  const dispatch =
    useRecipesDispatch();
  const star = recipe.favorite
    ? '★'
    : '☆';
  const items = recipe
    .ingredients.join(', ');
  // 5. 바꾸는 일은 위로 알리기
  function handleStar() {
    dispatch({
      type: 'toggledFavorite',
      id: recipe.id,
    });
  }
  function handleEdit() {
    onEdit(recipe.id);
  }
  function handleDelete() {
    dispatch({
      type: 'deleted',
      id: recipe.id,
    });
  }
  return (
    <li>
      <h3>{recipe.title}</h3>
      <p>{recipe.category}</p>
      <p>{recipe.minutes}분</p>
      <p>{items}</p>
      <button
        onClick={handleStar}
      >
        {star}
      </button>
      <button
        onClick={handleEdit}
      >
        고치기
      </button>
      <button
        onClick={handleDelete}
      >
        지우기
      </button>
    </li>
  );
}

export default RecipeCard;

src/RecipeList.jsx — 앞 레슨 그대로입니다.

src/RecipeList.jsx
import RecipeCard from
  './RecipeCard.jsx';

function RecipeList({
  recipes,
  onEdit,
}) {
  return (
    <ul>
      {recipes.map((r) => (
        <RecipeCard
          key={r.id}
          recipe={r}
          onEdit={onEdit}
        />
      ))}
    </ul>
  );
}

export default RecipeList;

src/SearchBar.jsx — 앞 레슨 그대로입니다.

src/SearchBar.jsx
function SearchBar({
  query,
  onQueryChange,
}) {
  return (
    <input
      placeholder="검색"
      value={query}
      onChange={(e) =>
        onQueryChange(
          e.target.value,
        )
      }
    />
  );
}

export default SearchBar;

src/CategoryFilter.jsx — 앞 레슨 그대로입니다.

src/CategoryFilter.jsx
import {
  categories,
} from './recipes.js';

const choices = [
  '전체',
  ...categories,
];

function CategoryFilter({
  category,
  onCategoryChange,
}) {
  const buttons = choices.map(
    (c) => (
      <button
        key={c}
        className={
          c === category
            ? 'active'
            : ''
        }
        onClick={() =>
          onCategoryChange(c)
        }
      >
        {c}
      </button>
    ),
  );
  return <div>{buttons}</div>;
}

export default CategoryFilter;

src/RecipeForm.jsx — 앞 레슨 그대로입니다.

src/RecipeForm.jsx
import {
  useState,
} from 'react';
import {
  categories,
} from './recipes.js';

const blank = {
  title: '',
  category: categories[0],
  minutes: '',
  ingredients: [],
  favorite: false,
};

function RecipeForm({
  recipe = blank,
  onSave,
}) {
  // 4. state 자리 정하기
  const [title, setTitle] =
    useState(recipe.title);
  const [picked, setPicked] =
    useState(recipe.category);
  const [minutes, setMinutes] =
    useState(recipe.minutes);
  function handleTitle(e) {
    setTitle(e.target.value);
  }
  function handlePick(e) {
    setPicked(e.target.value);
  }
  function handleMinutes(e) {
    setMinutes(e.target.value);
  }
  // 5. 바꾸는 일은 위로 알리기
  function handleSubmit(e) {
    e.preventDefault();
    const name = title.trim();
    if (name === '') return;
    onSave({
      ...recipe,
      id:
        recipe.id ??
        crypto.randomUUID(),
      title: name,
      category: picked,
      minutes: Number(minutes),
    });
    setTitle('');
    setMinutes('');
  }
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  const label = recipe.id
    ? '저장'
    : '더하기';
  return (
    <form
      onSubmit={handleSubmit}
    >
      <input
        placeholder="이름"
        value={title}
        onChange={handleTitle}
      />
      <select
        aria-label="분류"
        value={picked}
        onChange={handlePick}
      >
        {options}
      </select>
      <input
        type="number"
        placeholder="분"
        value={minutes}
        onChange={handleMinutes}
      />
      <button>{label}</button>
    </form>
  );
}

export default RecipeForm;

src/ListScreen.jsx — 앞 레슨 그대로입니다.

src/ListScreen.jsx
import {
  useState,
} from 'react';
import {
  useRecipes,
  useRecipesDispatch,
} from './useRecipes.js';
import useLocalStorage from
  './useLocalStorage.js';
import SearchBar from
  './SearchBar.jsx';
import CategoryFilter from
  './CategoryFilter.jsx';
import RecipeList from
  './RecipeList.jsx';
import RecipeForm from
  './RecipeForm.jsx';

function byTime(a, b) {
  return a.minutes - b.minutes;
}

function ListScreen() {
  const recipes = useRecipes();
  const dispatch =
    useRecipesDispatch();
  // 4. state 자리 정하기
  const [query, setQuery] =
    useState('');
  const [picked, setPicked] =
    useState('전체');
  const [editId, setEditId] =
    useState(null);
  const [sort, setSort] =
    useLocalStorage(
      'recipe-box:sort',
      'added',
    );
  // 3. 가장 작은 state 찾기
  const sorted =
    sort === 'fastest'
      ? recipes.toSorted(byTime)
      : recipes;
  const visible = sorted
    .filter(
      (r) =>
        r.title.includes(query),
    )
    .filter(
      (r) =>
        picked === '전체' ||
        r.category === picked,
    );
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  const editing = recipes.find(
    (r) => r.id === editId,
  );
  // 5. 바꾸는 일은 위로 알리기
  function handleSave(recipe) {
    dispatch({
      type: 'added',
      recipe,
    });
  }
  function handleUpdate(next) {
    dispatch({
      type: 'updated',
      recipe: next,
    });
    setEditId(null);
  }
  function handleSort(e) {
    setSort(e.target.value);
  }

  return (
    <section>
      <SearchBar
        query={query}
        onQueryChange={setQuery}
      />
      <CategoryFilter
        category={picked}
        onCategoryChange={
          setPicked
        }
      />
      <select
        aria-label="정렬"
        value={sort}
        onChange={handleSort}
      >
        <option value="added">
          더한 순
        </option>
        <option value="fastest">
          빠른 순
        </option>
      </select>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <RecipeList
        recipes={visible}
        onEdit={setEditId}
      />
      {editing && (
        <RecipeForm
          key={editing.id}
          recipe={editing}
          onSave={handleUpdate}
        />
      )}
      <RecipeForm
        onSave={handleSave}
      />
    </section>
  );
}

export default ListScreen;

src/TabBar.jsx — 앞 레슨 그대로입니다.

src/TabBar.jsx
function TabBar({ onTab }) {
  function toList() {
    onTab('list');
  }
  function toStats() {
    onTab('stats');
  }
  return (
    <nav>
      <button onClick={toList}>
        목록
      </button>
      <button onClick={toStats}>
        통계
      </button>
    </nav>
  );
}

export default TabBar;

src/StatsScreen.jsx — 앞 레슨 그대로입니다.

src/StatsScreen.jsx
import {
  useState,
} from 'react';
import {
  useRecipes,
  useRecipesDispatch,
} from './useRecipes.js';

function isRecipe(r) {
  return (
    typeof r?.id === 'string' &&
    typeof r.title ===
      'string' &&
    typeof r.category ===
      'string' &&
    typeof r.minutes ===
      'number' &&
    Array.isArray(
      r.ingredients,
    ) &&
    typeof r.favorite ===
      'boolean'
  );
}

function readBackup(text) {
  const data = JSON.parse(text);
  if (!Array.isArray(data)) {
    throw new Error(
      '레시피 목록이 아닙니다.',
    );
  }
  for (const r of data) {
    if (!isRecipe(r)) {
      throw new Error(
        '모양이 틀린 줄이 있습니다.',
      );
    }
  }
  return data;
}

function StatsScreen() {
  const recipes = useRecipes();
  const dispatch =
    useRecipesDispatch();
  // 4. state 자리 정하기
  const [text, setText] =
    useState('');
  const [message, setMessage] =
    useState('');
  // 3. 가장 작은 state 찾기
  const total = recipes.length;
  const sum = recipes.reduce(
    (s, r) => s + r.minutes,
    0,
  );
  const average =
    total === 0
      ? 0
      : Math.round(sum / total);
  const favoriteCount =
    recipes.filter(
      (r) => r.favorite,
    ).length;
  // 5. 바꾸는 일은 위로 알리기
  function handleText(e) {
    setText(e.target.value);
  }
  function handleExport() {
    const json =
      JSON.stringify(recipes);
    setText(json);
    setMessage('');
  }
  function handleImport() {
    try {
      const data =
        readBackup(text);
      dispatch({
        type: 'replacedAll',
        recipes: data,
      });
      setMessage(
        data.length +
          '개를 불러왔습니다.',
      );
    } catch (err) {
      setMessage(
        '불러오지 못했습니다: ' +
          err.message,
      );
    }
  }

  return (
    <section>
      <p>전체 {total}개</p>
      <p>평균 {average}분</p>
      <p>
        즐겨찾기 {favoriteCount}개
      </p>
      <textarea
        aria-label="백업"
        value={text}
        onChange={handleText}
      />
      <button
        onClick={handleExport}
      >
        내보내기
      </button>
      <button
        onClick={handleImport}
      >
        불러오기
      </button>
      <p>{message}</p>
    </section>
  );
}

export default StatsScreen;

src/App.jsx는 세 조각입니다. 첫 조각은 가져오기입니다.

src/App.jsx
import {
  useState,
} from 'react';
import RecipesProvider from
  './RecipesProvider.jsx';
import TabBar from
  './TabBar.jsx';
import ListScreen from
  './ListScreen.jsx';
import StatsScreen from
  './StatsScreen.jsx';

App은 view로 그릴 화면을 고릅니다. 앞 코드에 이어 씁니다.

src/App.jsx
function App() {
  const [view, setView] =
    useState('list');
  const screen =
    view === 'list' ? (
      <ListScreen />
    ) : (
      <StatsScreen />
    );

코드 아래 화면은 배포 판에서 '통계'를 누른 뒤 화면입니다. 찍어 둔 화면이라 눌러도 바뀌지 않습니다. 앞 코드에 이어 씁니다.

src/App.jsx
  return (
    <RecipesProvider>
      <main>
        <h1>레시피 보관함</h1>
        <TabBar
          onTab={setView}
        />
        {screen}
      </main>
    </RecipesProvider>
  );
}

export default App;
<main><h1>레시피 보관함</h1><nav><button>목록</button><button>통계</button></nav><section><p>전체 4개</p><p>평균 18분</p><p>즐겨찾기 2개</p><textarea aria-label="백업"></textarea><button>내보내기</button><button>불러오기</button><p></p></section></main>
결과 화면

src/App.jsx를 한 파일로 다시 실었습니다.

src/App.jsx
import {
  useState,
} from 'react';
import RecipesProvider from
  './RecipesProvider.jsx';
import TabBar from
  './TabBar.jsx';
import ListScreen from
  './ListScreen.jsx';
import StatsScreen from
  './StatsScreen.jsx';

function App() {
  const [view, setView] =
    useState('list');
  const screen =
    view === 'list' ? (
      <ListScreen />
    ) : (
      <StatsScreen />
    );
  return (
    <RecipesProvider>
      <main>
        <h1>레시피 보관함</h1>
        <TabBar
          onTab={setView}
        />
        {screen}
      </main>
    </RecipesProvider>
  );
}

export default App;

자주 틀리는 곳

틀린 생각: .env에 넣은 값이 묶음에서 찾아지지 않으니, 비밀 키를 둬도 된다.

찾아보기가 0곳인 것은 VITE_TEST를 읽는 코드가 없어서입니다. 읽는 줄을 하나 더하는 순간 묶음에 글로 들어갑니다(4절).

맞는 규칙: 비밀 키는 .env의 VITE_ 값에 넣지 않습니다. VITE_ 값에는 누구나 봐도 되는 값만 둡니다.

틀린 생각: .env의 이름은 아무렇게나 지어도 코드에서 읽힌다.

.env를 TEST=찾아보기로 두고 import.meta.env.TEST를 읽으면 undefined라 <p>가 비고, 콘솔은 조용합니다. 묶음에도 찾아보기는 0곳입니다.

맞는 규칙: 코드에서 읽을 환경 변수는 이름을 VITE_로 시작합니다.

틀린 생각: 개발 판에서 고친 레시피가 배포 판에도 있다.

개발 판(5173)에서 계란말이의 별을 눌러 즐겨찾기를 하나 늘린 뒤 배포 판(4173)을 처음 열면 2개입니다. 포트가 다른 배포 판은 저장소가 따로라, 빈 저장소에서 씨앗 넷을 꺼냅니다.

맞는 규칙: 저장소는 주소의 경로 앞부분(http://localhost:4173⁠처럼 포트까지)이 같은 쪽끼리만 나눠 씁니다. 그래서 포트가 다르면 따로이고, 경로(/recipe-box/)만 다르면 같은 저장소입니다. 올린 사이트도 처음 열면 빈 저장소에서 시작합니다.

확인 문제

1. 예제 끝 판을 npm run build로 빌드하고 npm run preview로 열어 두었습니다. src/App.jsx의 제목 레시피 보관함을 내 레시피로 고쳐 저장한 뒤, 미리 보기 쪽을 새로 고칩니다. 제목은 어떻게 보일까요?

  • ① 내 레시피
  • ② 레시피 보관함 그대로
  • ③ 하얀 화면
정답

②입니다. 미리 보기 서버는 dist/의 파일을 그대로 줍니다. src/를 고쳐도 dist/는 빌드한 때 그대로라, npm run build를 다시 쳐야 바뀝니다. 다시 빌드하면 미리 보기를 끄지 않아도, 새로 고친 쪽이 새 이름의 JS를 받아 내 레시피가 보입니다.

  • ① 미리 보기도 개발 서버처럼 src/를 그때그때 바꿔 준다고 본 것입니다. 그것은 npm run dev 쪽입니다(2절).
  • ③ src/와 dist/가 어긋나면 쪽이 깨진다고 본 것입니다. dist/는 빌드한 때의 파일만으로 섭니다.

2. 예제 끝 판(base: '/recipe-box/')으로 빌드한 dist/를 하위 경로가 아닌 사이트 뿌리 /에 올렸습니다. 이 서버는 없는 파일에 404를 줍니다. 사이트 뿌리 주소를 열면 어떻게 될까요?

  • ① 레시피 보관함 화면이 뜬다
  • ② 쪽 자체를 못 찾아 404가 뜬다
  • ③ 하얀 화면이고, JS · CSS가 404다
정답

③입니다. base가 /recipe-box/인 빌드의 index.html은 /recipe-box/assets/의 파일을 부릅니다. 뿌리에 올린 사이트에는 그 주소의 파일이 없어 JS · CSS가 404이고, 화면은 하얗습니다. base는 올릴 곳의 경로와 같아야 합니다.

  • ① index.html만 오면 뜬다고 본 것입니다. 화면은 index.html이 부르는 JS가 그립니다.
  • ② base가 index.html의 자리까지 바꾼다고 본 것입니다. index.html은 뿌리에 있어 200으로 옵니다.

3. 친구가 말합니다. ".env에 VITE_KEY=abc123을 두고 빌드했는데, 묶은 JS에서 abc123이 0곳이야. 그러니 비밀 키를 둬도 돼." 맞는 것은 무엇일까요?

  • ① 읽는 코드가 없으면 0곳일 뿐, 읽으면 묶음에 글로 들어간다
  • ② 맞다 — .env의 값은 빌드가 가려 묶음에 넣지 않는다
  • ③ 값 대신 이름 VITE_KEY로 들어가 있어 값으로는 못 찾는다
정답

①입니다. import.meta.env.VITE_KEY⁠를 읽는 줄을 더해 빌드하면 묶은 JS에 abc123이 한 곳 들어가고, VITE_KEY는 0곳입니다. 묶은 JS는 사이트를 여는 누구나 받으니, 비밀 키는 VITE_ 값에 넣지 않습니다.

  • ② 읽지 않은 판의 0곳을 모든 판으로 넓힌 것입니다. 읽는 순간 들어갑니다(4절).
  • ③ 빌드가 이름을 남긴다고 본 것입니다. 묶음에 이름 VITE_KEY는 없습니다.

컴퓨터에서 해 보기(선택) — 점수에 들지 않습니다. 폰으로만 보고 있다면 건너뛰세요.

  1. 예제 끝 판을 npm run build로 빌드하고 npm run preview로 엽니다. base를 따라 Local 줄 주소 끝에 /recipe-box/가 붙습니다. '통계'를 눌러 예제 화면과 견주고, Ctrl+C로 끕니다.
  2. vite.config.js의 base 줄을 지우고 저장한 뒤 npm run build를 칩니다. 이번에는 미리 보기를 아래 명령으로 켭니다. 미리 보기 서버가 dist/를 /recipe-box/ 아래에 놓아, 하위 경로에 올린 사이트처럼 줍니다.
터미널에 칠 것
npm run preview -- --base=/recipe-box/
  1. Local 줄 주소를 열면 하얀 화면이고, Network 판을 열고 새로 고치면 JS · CSS가 404입니다. Ctrl+C로 끄고 base 줄을 되살려 저장합니다.
  2. 프로젝트 맨 위 폴더에 .env 파일을 만들어 VITE_TEST=찾아보기 한 줄을 넣고 npm run build를 칩니다. 편집기에서 dist/assets/의 JS 파일을 열고 찾기(Ctrl+F · 맥은 ⌘F)로 찾아보기를 찾으면 없습니다. 그 파일은 열 줄도 안 되고, 빈칸이 빠져 한 줄이 아주 깁니다. 컴포넌트 이름도 줄어 RecipeCard가 se 같은 두 글자 함수가 됩니다(판에 따라 글자가 다릅니다).
  3. src/App.jsx는 먼저 메모 앱에 옮겨 두고, 4절의 두 조각을 넣어 저장한 뒤 다시 빌드합니다. 새 JS 파일에서 찾아보기를 찾으면 한 곳 나옵니다. 다 보면 App.jsx를 메모 앱 판으로 되돌리고 .env를 지운 뒤 다시 빌드합니다.

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

리액트 목차로