라우터 플러그인
Granite Router는 파일 기반 라우팅을 지원하고, 경로별 타입이 자동으로 지정되는 타입-세이프 라우터예요. pages/ 디렉토리에 파일을 추가하는 것만으로 화면을 만들 수 있어요.
페이지를 쉽게 생성하고 관리하려면 아래와 같이 플러그인을 설치하세요.
sh
$ npm install @granite-js/plugin-router --save-devsh
$ pnpm add @granite-js/plugin-router --save-devsh
$ yarn add @granite-js/plugin-router --dev다음은 router 플러그인을 granite.config.ts 설정에 추가하는 예시예요. 이 플러그인은 pages/ 폴더를 기반으로 경로(route)를 자동으로 만들어줘요.
ts
import { env } from '@granite-js/plugin-env';
import { hermes } from '@granite-js/plugin-hermes';
import { router } from '@granite-js/plugin-router';
import { defineConfig } from '@granite-js/react-native/config';
export default defineConfig({
/**
* granite://example
*/
scheme: 'granite',
appName: 'example',
plugins: [
router(),
],
});개발 모드
개발 모드에서는 페이지 파일을 새로 만들면 자동으로 화면 구성 코드와 타입 정의가 생성돼요.
sh
$ npx granite devsh
$ pnpm granite devsh
$ yarn granite dev예를 들어, pages/page-a.tsx 파일을 추가하면 다음과 같은 화면 컴포넌트와 라우팅 코드가 자동으로 생성돼요.
tsx
import React from 'react';
import { Text, View } from 'react-native';
import { createRoute } from '@granite-js/react-native';
export const Route = createRoute('/page-a', {
validateParams: (params) => params,
component: PageA,
});
function PageA() {
return (
<View>
<Text>Hello PageA</Text>
</View>
);
}이 페이지는 granite://example/page-a 경로로 접근할 수 있어요.
자동 생성된 타입 정의
Granite는 라우팅 경로에 대해 타입도 자동으로 정의해줘요. 덕분에 라우팅을 할 때 경로와 파라미터가 잘못되면 에러를 발생시켜요.
tsx
// src/router.gen.ts
/* eslint-disable */
// This file is auto-generated by @granite-js/react-native. DO NOT EDIT.
import { Route as _PageARoute } from '../pages/page-a';
import { Route as _PageBRoute } from '../pages/page-b';
import { Route as _PageCRoute } from '../pages/page-c';
declare module '@granite-js/react-native' {
interface RegisterScreenInput {
'/page-a': (typeof _PageARoute)['_inputType'];
'/page-b': (typeof _PageBRoute)['_inputType'];
'/page-c': (typeof _PageCRoute)['_inputType'];
}
interface RegisterScreen {
'/page-a': (typeof _PageARoute)['_outputType'];
'/page-b': (typeof _PageBRoute)['_outputType'];
'/page-c': (typeof _PageCRoute)['_outputType'];
}
}이렇게 자동 생성된 타입 정의를 사용하면 라우팅이 안전하고, 실수를 줄일 수 있어요.