본문으로 건너뛰기
튜토리얼

Building Mobile Apps with Pure React.js and Capacitor

A guide on how to transform a React.js web application into a native mobile app utilizing Capacitor, and adding Capgo Native Navigation, Transitions, and iOS layout best practices.

작성자

마틴 도나디유

리뷰어

발레리아

Article credits

조던

편집자

Building Mobile Apps with Pure React.js and Capacitor

This tutorial will walk you through crafting a mobile application using React and Capacitor. By the end, you’ll know how to morph a React.js web app into a native mobile application with Capacitor, and add a native feel with Capgo Native Navigation and Transitions.

Capacitor은 React.js 웹 앱을 모바일 애플리케이션으로 변환하는 것을 쉽게 만듭니다. React Native와 같은 새로운 전략을 배울 필요 없이, Capacitor을 사용하여 모바일 앱을 제작할 수 있습니다.

이 과정은 몇 가지 단순한 단계로 구성되어 있으며, 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__을 사용하여 프로젝트를 모바일 앱으로 변환하는 방법 export 앱의 이 부분은 필요합니다.

이것에 대해 다시 돌아올 것입니다. 일단, Capacitor을 React 앱에 통합하는 방법을 이해하는 것이 좋습니다.

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

초기 설정 단계는 조금 세세할 수 있지만, 그 이후로 네이티브 앱 wrapper를 업데이트하는 것은 단순히 명령어를 실행하는 것과 같습니다. sync command.

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.”

마지막으로, 플랫폼을 추가하고 __CAPGO_KEEP_0__은 프로젝트 루트에 각 플랫폼을 위한 폴더를 생성합니다:

마지막으로 플랫폼을 추가하고 Capacitor은 프로젝트 루트에 각 플랫폼을 위한 폴더를 생성합니다.

# 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

ios and context 안드로이드 디렉토리가 이제 React.js 프로젝트에 존재합니다.

앱을 나중에 액세스하려면 안드로이드 스튜디오를 설치하세요. Xcode.

Xcode 를 설치해야 합니다. 다음으로 capacitor.config.json 를 업데이트하세요.

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

Capacitor.config.json

npm run build
npx cap sync

The npm run build 명령은 React.js 프로젝트를 빌드하며 npx cap sync 은 웹 code을 원활한 위치에 배치하여 네이티브 플랫폼에서 실행할 수 있도록 합니다.

현재, React.js 앱이 기기에서 작동할 준비가 된 것입니다!

네이티브 앱 빌드 및 배포

iOS 앱을 개발하려면 Xcode를 사용해야 합니다. Android 앱을 개발하려면 안드로이드 스튜디오를 사용해야 합니다. 앱 스토어에 앱을 배포하려면 iOS는 Apple Developer Program에, Android는 Google Play Console에 가입해야 합니다.

Capacitor CLI은 네이티브 프로젝트를 열기 위한 프로세스를 단순화합니다:

npx cap open ios
npx cap open android

네이티브 프로젝트를 설정한 후 기기와 연결된 앱을 배포하는 것은 단순한 과정입니다.

안드로이드 스튜디오의 경우, 모든 것을 로드하고 앱을 연결된 기기로 배포하세요.

Xcode의 경우, 앱을 실제 기기에서만 시뮬레이터 대신 배포할 수 있도록 서명 계정 설정을 완료하세요. 그 후에 단순히 플레이 버튼을 클릭하여 연결된 기기에서 앱을 실행하세요. 기기를 선택할 수 있는 탑 부분에서 기기를 선택하세요.

모든 것이 잘 진행되었다면, React.js 웹 앱을 네이티브 모바일 애플리케이션으로 변환할 수 있습니다!

Capacitor 리로드

최신 개발 프레임워크는 일반적으로 핫 리로드를 제공하며, Capacitor도 같은 기능을 제공할 수 있습니다. 하지만 __CAPGO_KEEP_0__는 모바일 기기에서만 작동합니다.!

로컬 호스트된 애플리케이션에 라이브 리로드를 적용하여 네트워크 내에서 앱을 접근할 수 있습니다. Capacitor 앱이 특정 URL에서 콘텐츠를 로드하도록 설정하면 됩니다.

먼저 로컬 IP 주소를 확인하세요. 맥의 경우 터미널에서 실행하면 되고, 윈도우의 경우 명령 프롬프트에서 실행하여 IPv4 주소를 확인하세요. ipconfig getifaddr en0 터미널에서 실행합니다. 윈도우에서 실행하려면 ipconfig __CAPGO_KEEP_0__ Live Update

이후에는 Capacitor에 앱을 서버에서 직접 로드하도록 하기 위해 서버에서 앱을 로드하는 파라미터에 추가하는 방법을 설명합니다. capacitor.config.ts Capacitor

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 이 변경 사항을 우리의 네이티브 프로젝트에 적용하려면

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

새로운 플러그인이 설치된 경우, 예를 들어 카메라 플러그인이 설치된 경우, 네이티브 프로젝트를 다시 빌드해야 합니다. 이는 네이티브 파일이 변경되었기 때문입니다. 동적 업데이트가 불가능하기 때문입니다.

Capacitor 플러그인 사용

Capacitor 플러그인을 사용하는 방법에 대해 간단히 살펴보겠습니다. 간단한 플러그인인 Share 플러그인을 설치해 보겠습니다. 이 플러그인은 네이티브 공유 대화 상자를 표시합니다:

npm i @capacitor/share

이를 사용하려면 패키지를 임포트하고 앱에서 해당 share() function을 호출합니다. App.js:

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;

새로운 플러그인을 설치한 후, React 프로젝트를 다시 싱크해야 합니다. npx cap sync.

다음으로, iOS 및 Android에서 앱이 더 원시적인 느낌을 줄 수 있도록 Capgo 네비게이션 및 전환을 사용하고, 수평 스크롤이나 안전 영역이 잘려나가는 iOS 레이아웃 문제를 해결할 수 있습니다.

원시적인 UI를 위한 Capgo 네이티브 네비게이션 및 전환

수년간 Ionic을 사용하여 크로스 플랫폼 앱을 개발해 왔습니다. Ionic Tailwind CSS와 함께 React를 통합하는 것은 복잡하고 거의 가치가 없습니다. Tailwind CSS만 사용하면 충분합니다. React + __CAPGO_KEEP_0__ 앱에서 원시적인 모바일 느낌을 얻으려면 __CAPGO_KEEP_1__ 플러그인을 사용하는 것이 좋습니다. 웹 전용 UI 키트인 Konsta UI와 같은 대안은 사용하지 마세요..

@Capacitor/Capgo-native-navigation

Capacitor

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',
  },
});

리퀴드 글라스 탭 바를 렌더링하세요 (iOS는 시스템 소유 렌더링을 사용하고 Android는 흐린 웹뷰 백그라운드 사용):

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>;
}

페이지를 wrapping하여 cap-router-outlet, cap-page그리고 cap-content호출하세요: setDirection('forward') 또는 setDirection('back') 네이티브 바를 존중하도록 웹 콘텐츠가 네이티브 바를 존중하도록 하세요. 네이티브 네비게이션은 웹 헤더 또는 푸터를 중복하지 마세요.

자세한 가이드를 참조하세요: @capgo/capacitor-자연스러운 네비게이션 그리고 @capgo/capacitor-transition.

안전 영역에 Tailwind

Tailwind CSS에서 장치 안전 영역을 사용하려면 @capgo/tailwind-capacitor Tailwind CSS에서 장치 안전 영역을 사용하려면 tailwind-capacitor Capacitor를 사용하여 React로 모바일 앱을 만들기 위해 npm). 그것은 safe-areas utility 및 다른 Capacitor-친화 Tailwind 플러그인

bun add -D tailwind-capacitor

In src/index.css:

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

Tailwind CSS에서 장치 안전 영역을 사용하려면 pt-safe, pb-safe, and px-safe Tailwind CSS에서 장치 안전 영역을 사용하려면 env(safe-area-inset-*) Tailwind CSS에서 장치 안전 영역을 사용하려면 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 안전 영역을 한 번에 처리하라.

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

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-capacitorReact와 Capacitor을 사용하여 모바일 앱을 만들 수 있습니다. pt-safe pb-safe px-safe 단일 셸에서 동일한 패딩을 표현할 수 있습니다.

Capacitor iOS contentInset to never 첫 번째

In capacitor.config.tsCSS 또는 Native Navigation의 안전 영역을 제어하는 것이 좋습니다. contentInsetMode: 'css'__CAPGO_KEEP_0__의 자동 콘텐츠 인셋과 CSS 패딩을 혼합하는 것은 일반적인 더블 스페이싱의 원인입니다.

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

Mixing Capacitor’s automatic content inset with CSS env(safe-area-inset-*) 일반적으로 요소가 사용하는 것이 원인입니다.

__CAPGO_KEEP_0__

첫 번째 100vwTailwind w-screen픽셀 너비의 고정 너비 또는 대형 min-width.

In 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, duplicated safe-area padding, 또는 고정 너비의 컨테이너 — viewport meta 태그 자체에서 아님.

결론

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

Capacitor과 같은 기술 덕분에, React.js 웹 앱으로부터 모바일 애플리케이션을 빌드하는 것은 절대 쉬워졌습니다. 웹 개발 기술을 다음 단계로 끌어올리기 위해, 훌륭한 네이티브 모바일 앱을 제작하세요. HAPPY CODING!

더욱 빠른 앱 개발 프로세스를 위해 무료 계정으로 가입하십시오 오늘.

Pure React.js와 함께 모바일 앱을 만들기 위한 Capacitor

Pure React.js와 함께 모바일 앱을 만들기 위해 사용 중이라면 Pure React.js와 함께 모바일 앱을 만들기 위한 Capacitor __CAPGO_KEEP_0__/__CAPGO_KEEP_1__-live-activities를 사용하여 capgo/capacitor-live-activities를 사용하여 capgo/capacitor-live-activities capgo/capacitor-live-activities를 사용하여 capgo/capacitor-video-player를 사용하여 capgo/capacitor-video-player를 사용하여 capgo/capacitor-video-player capgo/capacitor-video-player for capgo capacitor-video-player 구현 세부사항에 대해 @capgo/capacitor-자연스러운 네비게이션 Capacitor의 네이티브 네비게이션을 사용하여 @capgo/capacitor 네이티브 기능을 위해.

Capacitor 앱의 즉각 업데이트

Capgo 앱의 즉각 업데이트

웹-layer 버그가 활성화된 경우, 앱 스토어 승인 대기 없이 __CAPGO_KEEP_0__를 통해 패치를 배포하세요. 사용자는 배경에서 업데이트를 받으며 네이티브 변경 사항은 일반적인 검토 경로를 유지합니다.

마틴의 인간 지원

시작하기

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