DEV Community

Masui Masanori
Masui Masanori

Posted on

Try Vite + React + Tailwind CSS

Intro

This time, I will try creating a React application by Vite.
And I will also try using Tailwind CSS.

Creating a React project

First, I will create a React project using Vite by following the "Getting Started".

npm create vite@latest my-react-app -- --template react-ts
Enter fullscreen mode Exit fullscreen mode

After creating the project, I will install Tailwind CSS, PostCSS, autoprefixer.

To use TailWind CSS, I should execute "npx tailwindcss init" and add "postcss.config.js".

postcss.config.js

export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}
Enter fullscreen mode Exit fullscreen mode

And I change the "tailwind.config.js" like below.

tailwind.config.js

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Enter fullscreen mode Exit fullscreen mode

After that, I also need to add these three rows into "index.css".

index.css

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

...
Enter fullscreen mode Exit fullscreen mode

To avoid "Unknown at rule @tailwind" on VSCode, I should install "Tailwind CSS IntelliSense" and add "Files: Associations" into VSCode settings.

warning

Image description

settings.json

Image description

After installing, I can write like below.

App.tsx

import "./App.css";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link
} from "react-router-dom";
import { IndexPage } from "./IndexPage";

function App() {
  return (
    <>
      <div className="w-full h-screen flex flex-col items-center justify-center">
        <div className="w-[86%] h-[90%] bg-[green]">
          <Router>
            <Link to="/">TOP</Link>
            <Routes>
              <Route path="/" element={<IndexPage />} />
            </Routes>
          </Router>
        </div>
      </div>     
    </>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

Environmental variables

I can use environmental variables by ".env", ".env.development(for development)", and ".env.production(for production)".
In Vite projects, variable names have to be prefixed with "VITE_".

.env

VITE_SERVER_APP_URL="http://localhost:3000"
Enter fullscreen mode Exit fullscreen mode

I can get the value like below.

Index.page.tsx

import "./IndexPage.css";
import { useEffect, useState } from "react";

export function IndexPage(): JSX.Element {
  useEffect(() => {
    fetch(`${import.meta.env.VITE_SERVER_APP_URL}/pointclouds`, {
      mode: "cors",
      method: "GET"
    }).then(res => res.json())
    .then(res => console.log(res))
    .catch(err => console.error(err));
  }, []);
...
}
export default IndexPage;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)