React NativeでTailwind CSSを使用したいので、nativewindを導入した

目次

React NativeTailwind CSSを使用したいということで調べてみると下記2つが該当した。

tailwind-rnとnativewindの比較

スターはtailwind-rnが上回っているけど、活動の多さではnativewindが上回っているようなので、nativewindを採用した。

nativewindの導入

ドキュメントも丁寧なのでなぞって行っていく。

npm i nativewind
npm i --dev tailwindcss

上記コマンドで該当パッケージをインストールする。

npx tailwindcss init

次に上記コマンドでtailwind.config.jsを作成し、下記のように記載する。

// tailwind.config.js

module.exports = {
- content: [],
+ content: ["./App.{js,jsx,ts,tsx}", "./<custom directory>/**/*.{js,jsx,ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
}

<custom directory>は自身のディレクトリに編集する。

次にbabel.config.jsを下記のように編集していく。

// babel.config.js
module.exports = function (api) {
  api.cache(true);
  return {
    presets: ["babel-preset-expo"],
+   plugins: ["nativewind/babel"],
  };
};

以上とのことなので、起動してみる。
無事に開発環境は動いている。

次にnativewindの記述を反映することができるか確認してみる。

    <View style={styles.container}>
      <Text>Hello World!</Text>
      <StatusBar style="auto" />
    </View>

    <View className="flex-1 items-center justify-center bg-white">
      <Text>Hello World!</Text>
      <StatusBar style="auto" />
    </View>

に変換した。結果大量のエラーが出現した。

No overload matches this call.
  Overload 1 of 2, '(props: ViewProps | Readonly<ViewProps>): View', gave the following error.
    Type '{ children: Element[]; className: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps>'.
      Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps>'.
  Overload 2 of 2, '(props: ViewProps, context: any): View', gave the following error.
    Type '{ children: Element[]; className: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps>'.
      Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<View> & Readonly<ViewProps>'.ts(2769)

エラーの解消

エラーを解消していく。

そもそもnativewindexpoで使用するサンプルがGithubに用意されていたので、それを見つつ解消していく。

まず最初に変更したtailwind.config.js

content: ["./App.tsx"],

に変更する。

次に、babel.config.jsはそのまま。

で、ここまでで不足しているっぽいファイルを追加していく。

まずは、styles.cssをルートに追加する。
内容は

@tailwind base;
@tailwind components;
@tailwind utilities;

あとnativewind.d.tsという型ファイル。

中身は

/// <reference types="nativewind/types" />

これにの追加によりclassNameの型エラーが解消された。

最後にapp.tsxにimport "./styles.css";という感じで追加したstyle.cssをインポートする。

で、実行すると

error: App.tsx: ~\App.tsx: Use process(css).then(cb) to work with async plugins

というエラーが出た。
https://github.com/marklawlor/nativewind/issues/556 も上がっている。

過去issueで解決済だったので、それを参照し
tailwindのバージョンを”^3.3.2”に変更したところ、

error: App.tsx: ~\App.tsx: Use process(css).then(cb) to work with async plugins

このエラーは消えた。

次に、下記エラーと遭遇する。

Unable to resolve "./styles.css" from "App.tsx"

このエラーはApp.tsximport "./styles.css";を削除したら消えた。

動作確認

最後に起動したところ、無事にnativewindの記述が反映されていることを確認できた。

次に読むおすすめ記事

nth-childとnth-of-typeの違いを理解する

この記事に対するコメント

お気軽にコメントを下さい

メールアドレスが公開されることはありません。 が付いている欄は必須項目です