메인 콘텐츠로 바로가기
튜토리얼

Capacitor을 사용한 순수 React.js로 모바일 앱을 빌드하는 방법

Capacitor을 사용하여 React.js 웹 애플리케이션을 네이티브 모바일 앱으로 변환하는 방법에 대한 안내서입니다. 또한 Capgo Native Navigation, Transitions, 및 iOS 레이아웃 최적화 방법에 대해 설명합니다.

Martin Donadieu

Martin Donadieu

콘텐츠 마케터

React.js와 Capacitor를 사용한 모바일 앱 개발

이 튜토리얼에서는 React와 Capacitor를 사용하여 모바일 애플리케이션을 제작하는 방법을 안내합니다. 튜토리얼을 마치면 React.js 웹 앱을 Capacitor로 변환하고 Capgo Native Navigation and Transitions를 사용하여 네이티브한 느낌을 줄 수 있을 것입니다.

Capacitor는 React.js 웹 앱을 네이티브 모바일 애플리케이션으로 변환하는 것을 쉽게 해주며, 새로운 전략이나 React Native와 같은 것들을 배울 필요가 없습니다.

이 과정은 몇 가지 단순한 단계로 구성되어 있으며, React.js 앱이 완전히 작동하는 모바일 애플리케이션으로 변환되기까지는 시간이 걸리지 않습니다. 따라서 이 여정을 따라가면서 안내해 드리겠습니다.

Capacitor 개요

CapacitorJS는 게임 체이너입니다. 웹 프로젝트와 완벽하게 통합할 수 있으며, 네이티브 웹뷰로 앱을.wrap하고 네이티브 Xcode와 Android Studio 프로젝트를 생성할 수 있습니다. 또한, 플러그인을 통해 카메라와 같은 네이티브 장치 기능에 접근할 수 있습니다.

Capacitor는 네이티브 모바일 애플리케이션을 만들기 위한 단순한 방법을 제공합니다. API와 streamlined 기능을 통해 프로젝트에 쉽게 통합할 수 있습니다.

React.js 앱 설정

React 애플리케이션을 시작하는 가장 단순한 방법을 사용해 보겠습니다. npm 패키지 매니저를 사용하여 새로운 React 앱을 생성할 것입니다:

npx create-react-app my-app

프로젝트를 네이티브 모바일 앱으로 변환하기 위해, 앱의 내보내기가 필요합니다. __CAPGO_KEEP_0__ 이것에 대해 다시 돌아올 것입니다. 일단, __CAPGO_KEEP_0__을 React 앱에 통합하는 방법을 이해해 보겠습니다.

Capacitor을 React.js 앱에 통합하는 방법

초기 설정 단계가 조금 세세할 수 있지만, 그 이후로 네이티브 앱 wrapper를 업데이트하는 것은 Capacitor을 실행하는 것만큼 간단합니다.

첫 번째로, __CAPGO_KEEP_0__ __CAPGO_KEEP_1__을 개발 의존성으로 설치하고 프로젝트 내에서 설정합니다. 설정 중 이름과 번들 ID의 기본값을 수락하기 위해 “enter”를 눌러주세요. sync 다음으로, 코어 패키지와 iOS 및 Android 플랫폼에 관련된 패키지를 설치합니다.

First, we’ll install the Capacitor CLI as a development dependency and set it up within our project. During the setup, accept the default values for name and bundle ID by pressing “enter.”

네이티브

Finally, we’ll add the platforms, and Capacitor will create folders for each platform at our project root:

# Install the Capacitor CLI locally
npm install -D @capacitor/cli

# Initialize Capacitor in your React project
npx cap init

# Install the required packages
npm install @capacitor/core @capacitor/ios @capacitor/android

# Add the native platforms
npx cap add ios
npx cap add android

__CAPGO_KEEP_0__ __CAPGO_KEEP_1__ and android __CAPGO_KEEP_0__ 디렉토리가 React.js 프로젝트에 생성됩니다.

애플리케이션을 나중에 Android 프로젝트에 접근하기 위해 Android Studio설치해야 합니다. iOS의 경우 Mac가 필요하며.

Xcode 설치를 해야합니다. 다음으로 capacitor.config.json __CAPGO_KEEP_0__의

{
  "appId": "com.example.app",
  "appName": "my-app",
  "webDir": "build",
  "bundledWebRuntime": false
}

Capacitor 명령을 실행하고 프로젝트를 Capacitor와 동기화하세요.

npm run build
npx cap sync

The npm run build __CAPGO_KEEP_0__는 React.js 프로젝트를 빌드하며 npx cap sync 는 네이티브 플랫폼의 정확한 위치에 웹 code를 정렬하여 앱에서 실행할 수 있도록 합니다.

이제, 조금의 행운과 오류가 없다면, React.js 앱이 기기에 출시 준비가 된 것입니다!

네이티브 앱을 빌드하고 배포하는 방법

iOS 앱을 개발하려면 Xcode, Android 앱을 개발하려면 Android Studio가 필요합니다. 앱 스토어에서 앱을 배포하려면 iOS는 Apple Developer Program에, Android는 Google Play Console에 등록해야 합니다.

Capacitor CLI는 네이티브 프로젝트를 모두 열기 위한 과정을 단순화합니다:

npx cap open ios
npx cap open android

__CAPGO_KEEP_0__

Once your native projects are set up, deploying your app to a connected device is a straightforward process.

For Android Studio, wait for everything to load and then deploy your app to a connected device.

For Xcode, establish your signing account to deploy your app to a real device instead of just the simulator. After doing that, simply hit play to run the app on your connected device, which you can choose at the top.

Capacitor Live Reload

Capacitor Live Reload Modern development frameworks usually come with hot reload, and luckily, you can have the same with __CAPGO_KEEP_0__ but!

You can make your locally hosted application accessible with live reload on your network by having the Capacitor app load the content from a specific URL.

You can make your locally hosted application accessible with live reload on your network by having the __CAPGO_KEEP_0__ app load the content from a specific URL. ipconfig getifaddr en0 First, determine your local IP address. On a Mac, you can do it by running ipconfig in the terminal. On Windows, execute

and look for the IPv4 address. After this, instruct Capacitor to load the app directly from the server by adding another parameter to your capacitor.config.ts file:

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  appId: 'com.example.app',
  appName: 'my-app',
  webDir: 'build',
  bundledWebRuntime: false,
  server: {
    url: 'http://192.168.x.xx:3000',
    cleartext: true
  }
};

export default config;

정확한 IP와 포트를 사용하십시오. Run npx cap copy native 프로젝트에 이러한 변경 사항을 적용하려면

Android Studio 또는 Xcode를 통해 앱을 다시 배포할 때, React 앱의 변경 사항은 자동으로 로드되고 앱에 표시됩니다!

새로운 플러그인을 설치하는 경우, 카메라와 같은 경우, native 프로젝트를 다시 빌드해야 합니다. 이는 native 파일이 변경되었기 때문입니다. native 파일은 실시간으로 업데이트할 수 없습니다.

Capacitor 플러그인 사용

Capacitor 플러그인을 사용하는 방법에 대해 간단히 살펴보겠습니다. 간단한 플러그인을 설치해 보겠습니다. 공유 플러그인 , native 공유 대화창을 표시합니다.사용하려면 패키지를 임포트하고, 앱에서 해당

npm i @capacitor/share

함수를 호출하세요. App.js share() 을 고려하세요. __CAPGO_KEEP_0__:

import { Share } from '@capacitor/share';

function ShareButton() {
  const share = async () => {
    await Share.share({
      title: 'React App',
      text: 'Visit this React App',
      url: 'http://localhost:3000',
      dialogTitle: 'Share with...'
    });
  };

  return (
    <button onClick={share}>
      Share
    </button>
  );
}

export default ShareButton;

After __CAPGO_KEEP_0__ 설치 후 React 프로젝트를 다시 동기화하세요. npx cap sync.

다음으로, iOS 및 Android에서 Capgo 네비게이션 및 전환을 사용하여 앱을 더 원시적으로 느끼게 만들고, 수평 스크롤이나 안전 영역이 잘려나가는 iOS 레이아웃 문제를 해결하세요.

원시적인 UI 경험을 Capgo 네이티브 네비게이션 및 전환과 함께 사용하세요.

__CAPGO_KEEP_0__와 함께 10년 이상 작업했습니다. __CAPGO_KEEP_0__를 사용하여 크로스 플랫폼 애플리케이션을 빌드하는 데 __CAPGO_KEEP_1__을 사용했습니다. 하지만 React와 __CAPGO_KEEP_0__를 통합하는 것은 __CAPGO_KEEP_1__을 사용하는 것보다 더 많은 노력을 필요로하고, 이미 __CAPGO_KEEP_2__를 사용하고 있다면 가치가 없습니다. React + __CAPGO_KEEP_0__ 앱에서 원시적인 모바일 경험을 얻으려면 __CAPGO_KEEP_1__ 플러그인을 사용하세요. 웹 전용 UI 키트인 __CAPGO_KEEP_3__ UI와 같은 대안을 사용하는 것보다..

@Capacitor/Capgo-native-navigation

설치하기:

bun add @capgo/capacitor-native-navigation @capgo/capacitor-transitions
bunx cap sync

CSS inset 모드를 사용하여 네이티브 바를 존중하는 웹 콘텐츠를 네이티브 네비게이션과 구성하십시오:

import { NativeNavigation } from '@capgo/capacitor-native-navigation';

await NativeNavigation.configure({
  contentInsetMode: 'css',
  animationDuration: 360,
  glass: {
    effect: 'liquidGlass',
  },
});

Liquid Glass 탭 바를 렌더링하십시오 (iOS는 시스템 소유 렌더링을 사용하고 Android는 흐린 WebView 백그라운드 이미지를 사용합니다):

await NativeNavigation.setTabbar({
  selectedId: 'home',
  labelVisibilityMode: 'labeled',
  icons: true,
  colors: { dynamic: true },
  tabs: [
    { id: 'home', title: 'Home', icon: { svg: '...' } },
    { id: 'settings', title: 'Settings', icon: { svg: '...' } },
  ],
});

await NativeNavigation.addListener('tabSelect', ({ id }) => {
  navigate(`/${id}`);
});

앱 셸에서 네이티브 페이지 전환을 추가하십시오:

import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import '@capgo/capacitor-transitions';
import { initTransitions, setDirection, setupRouterOutlet } from '@capgo/capacitor-transitions/react';

initTransitions({ platform: 'auto' });

export function AppShell() {
  const navigate = useNavigate();
  const outletRef = useRef<HTMLElement>(null);

  useEffect(() => {
    if (outletRef.current) {
      setupRouterOutlet(outletRef.current, { platform: 'auto', swipeGesture: 'auto' });
    }
  }, []);

  const openSettings = () => {
    setDirection('forward');
    navigate('/settings');
  };

  return <cap-router-outlet ref={outletRef}>{/* routes */}</cap-router-outlet>;
}

루트된 페이지를 cap-router-outlet, cap-page, cap-content, setDirection('forward') , setDirection('back') ,

, Using @capgo/capacitor-native-navigation , Using @capgo/capacitor-transitions.

안전 영역에 대한 Tailwind

Tailwind CSS에서 장치 안전 영역을 사용하려면 @capgo/tailwind-capacitor (__CAPGO_KEEP_0__에서 발표됨). 이 플러그인은 tailwind-capacitor npm-친화적인 Tailwind 플러그인으로 safe-areas utilities and other Capacitor-friendly Tailwind plugins:

bun add -D tailwind-capacitor

Tailwind의 src/index.css:

@import 'tailwindcss';
@plugin "@capgo/tailwind-capacitor/platform";
@plugin "@capgo/tailwind-capacitor/safe-areas";

, pt-safe, pb-safe를 사용하는 대신 px-safe 수동으로 env(safe-area-inset-*) 프로젝트는 활발히 개발 중입니다. React 설정에 필요한 것이 빠진 경우 GitHub에 PR을 열기.

iOS 레이아웃 문제를 해결하는 방법 (뷰포트, 안전 영역, 가로 스크롤)

iOS에서 콘텐츠가 잘려나거나-shifted되거나 가로 스크롤이 가능하다면 overflow-x: hidden 뷰포트 태그를 더 추가하거나 수정하는 것만으로는 문제를 해결할 수 없다. 이러한 체크를 순서대로 진행하라.

뷰포트 메타 태그가 올바르게 적용되었는지 확인하라

뷰포트 메타 태그를 index.html 내부 <head>:

<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />

iOS 안전 영역을 한 개의 루트 wrapper에서만 처리하라

싱글 앱 셸을 생성하고 안전 영역 패딩을 거기에 적용하라 — 여러 개의 중첩된 컴포넌트에 적용하지 마라:

html,
body,
#root {
  width: 100%;
  min-height: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

* {
  box-sizing: border-box;
}

.app-shell {
  min-height: 100dvh;
  width: 100%;
  padding-top: env(safe-area-inset-top);
  padding-right: env(safe-area-inset-right);
  padding-bottom: env(safe-area-inset-bottom);
  padding-left: env(safe-area-inset-left);
}

모든 페이지 콘텐츠를 .app-shell안에 감싸라.

중복된 안전 영역 패딩이 헤더, 모달, 레이아웃 wrapper에 적용되어 UI가 잘려나거나 너무 크게 보인다면 @capgo/tailwind-capacitor, __CAPGO_KEEP_0__을 사용하여 동일한 패딩을 표현할 수 있습니다. pt-safe pb-safe px-safe 단일 셸에서 "on that single shell."를 입력합니다.

Capacitor iOS contentInset 첫 번째 never __CAPGO_KEEP_0__를 사용하여 첫 번째로 설정합니다.

native inset이 비활성화된 경우 CSS (또는 Native Navigation의) capacitor.config.ts)가 안전 영역을 관리하도록 허용합니다. contentInsetMode: 'css'__CAPGO_KEEP_0__의 자동 콘텐츠 인셋과 CSS 패딩을 혼합하는 것은 두 배의 간격이 발생하는 일반적인 원인입니다.

const config: CapacitorConfig = {
  appId: 'com.example.myapp',
  appName: 'my-app',
  webDir: 'build',
  ios: {
    contentInset: 'never',
  },
};

Capacitor의 실제로 넘치는 요소를 찾습니다. env(safe-area-inset-*) __CAPGO_KEEP_0__

__CAPGO_KEEP_1__

일반적인 원인은 요소가 사용하는 100vw, Tailwind w-screen, 고정 픽셀 너비, 또는 큰 min-width.

Safari Web Inspector에서 실행:

[...document.querySelectorAll('*')]
  .filter(el => el.scrollWidth > document.documentElement.clientWidth)
  .map(el => ({
    el,
    tag: el.tagName,
    class: el.className,
    scrollWidth: el.scrollWidth,
    clientWidth: document.documentElement.clientWidth,
  }));

Tailwind와 함께 w-screen 가능한 경우 w-full 대부분의 가로 스크롤 문제는 100vw / w-screen, 중복된 안전 영역 패딩, 또는 고정 너비 컨테이너 — viewport meta 태그 자체가 아니라 —에서 발생합니다.

결론

Capacitor은 기존 웹 프로젝트에 기반한 네이티브 앱을 빌드하는 데 완벽한 수단을 제공하며, 간단한 방법으로 code을 공유하고 일관된 UI를 제공합니다.

Capacitor과 같은 기술 덕분에, React.js 웹 앱으로부터 모바일 앱을 빌드하는 것은 절대 쉬운 일이 아닙니다. 웹 개발 기술을 다음 단계로 끌어올리려면, 훌륭한 네이티브 모바일 앱을 제작하세요. Happy coding!

앱 개발 프로세스를 가속화하는 방법에 대한 자세한 내용은 __CAPGO_KEEP_0__에 대한 무료 계정으로 가입하세요. __CAPGO_KEEP_1__.

Capacitor에서 Pure React.js로 모바일 앱을 빌드하고 Capacitor에서 계속 진행하세요.

만약 __CAPGO_KEEP_0__을 사용 중이라면 Pure React.js로 모바일 앱을 빌드하고 Capacitor에서 계속 진행하세요. __CAPGO_KEEP_0__을 사용하여 네이티브 미디어 및 인터페이스 동작을 계획하고 __CAPGO_KEEP_0__으로 연결하세요. capgo/capacitor-live-activities를 사용하여 capgo에서 네이티브 기능을 사용하세요. capgo/capacitor-live-activities를 사용하여 capgo에서 네이티브 기능을 사용하세요. capgo/capacitor-live-activities를 사용하여 capgo에서 구현 세부 정보를 사용하세요. capgo/capacitor-video-player를 사용하여 capgo에서 네이티브 기능을 사용하세요. capgo/capacitor-video-player를 사용하여 capgo에서 네이티브 기능을 사용하세요. capgo/capacitor-video-player를 사용하여 capgo에서 구현 세부 정보를 사용하세요. @capgo/capacitor-video-player capgo 구현 세부 사항은 @capgo/capacitor-video-player에서 확인할 수 있습니다. @capgo/capacitor-native-navigation을 사용하여 @capgo/capacitor-native-navigation의 네이티브 기능을 사용하여.

Capacitor 앱에 대한 실시간 업데이트

웹-layer 버그가 활성화된 경우 Capgo을 통해 픽스를 배포하는 대신 앱 스토어 승인까지 며칠 기다리지 말고.

시작하기

블로그에서 최신 뉴스

Capgo은 전문적인 모바일 앱을 만들기 위해 필요한 최고의洞察력을 제공합니다.