React Native Library with Typescript #
I keep using TDSX tool. At packages execute:
npx tsdx create ui-mobileI choose react template. Here I am not going to use storybook since it will not work so well, directly, with react-native components. Next, I will use react-native-web for that and to make possible to interop our ui components between web and mobile.
I Update packages/ui-mobile/package.json name to @mr/ui-mobile:
"name": "@mr/ui-mobile",Add react-native as dev dependency and according types for typescript:
yarn lerna add react-native --scope=@mr/ui-mobile --devyarn lerna add @types/react-native --scope=@mr/ui-mobile --devCreate the same BookCard component, created previously for web:
src/components/BookCard/index.tsx
import React from 'react';
import { View, Text } from 'react-native';
export default function BookCard({ book }: { book: any }) {
return (
<View>
<Text>{book.title}</Text>
<Text>{book.author}</Text>
<Text>{book.tag}</Text>
</View>
);
}
Again, I am using the book: any. I should be fixed to use our own IBook type. Update public Api of this library:
src/index.tsx
import BookCard from './components/BookCard';
export { BookCard };
Now, we update our mobile package to use our new library. Make sure it was built before, using yarn lerna run build:
yarn lerna add @mr/ui-mobile --scope=@mr/mobileUse BookCard on packages/mobile/App.tsx:
import React from "react";
import { allBooks } from "@mr/utils";
import { BookCard } from "@mr/ui-web";
function App() {
return (
<div>
<h1>List of Books</h1>
<ul>
{allBooks().map(function renderBook(book) {
return (
<li key={book.id}>
<BookCard book={book} />
</li>
);
})}
</ul>
</div>
);
}
export default App;
Metro watcher started having some conflits among libraries and node_modules folder. I go back to use WML instead, and link those libs to be copied to node_modules of our mobile package:
wml add packages/utils packages/mobile/node_modules/@mr/utilswml add packages/utils packages/mobile/node_modules/@mr/typeswml add packages/ui-mobile packages/mobile/node_modules/@mr/ui-mobilewml startI am with some problems, in some situations:
[error] unable to resolve root /Users/blah/project: directory /Users/blah/project is not watchedIt is reported here. I had to do something like this, for two of the links:
watchman watch packages/utilswatchman watch packages/ui-mobileAnd then
wml startSeems to be working well now. It is not a pretty solution, neither easy to setup, but I think it is a minor price to pay for hot reload with react-native. Hot reload is something we do not have on native development for mobile.
However, I will need to get a better solution for CI / CD.
Published