taylorbell.com

Getting Started with Next.js

I'm experimenting with creating a SaaS project with Next.js, Firebase, and Stripe.

Installing Next.js

The installation instructions on Next's "Getting Started" page make use of npm's package runner npx to run create-next-app.

npx create-next-app

However, I had already created a directory and written a README.md file (ala Tom Preston-Werner's "Readme Driven Development" article), so I opted for a manual installation.

yarn add next react react-dom

The instructions then have us add some scripts to the package.json file:

// inside of package.json
{
  "dependencies": {
    "next": "^10.0.8",
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "scripts" {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

Creating a Home Page Placeholder

Next.js uses filesystem routing where any .js file inside of a pages/ directory becomes a route on the site.

So we create a pages directory with an index.js file inside.

mkdir pages
touch pages/index.js

index.js will have a placeholder <Home/> component for the time being:

function Home() {
  return (
    <div>
      Home Page
    </div>
  )
}

export default Home

Next.js automatically imports React for us so we can write JSX.

Override the App component

In the docs for adding Tailwind to Next.js, they suggest importing the CSS inside of the pages/_app.js fie.

This is the location of Next's "Custom App" component, which enables global CSS to be added (among other things.)

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

Installing Tailwind CSS

Tailwind is another thing that I want more practice with. Their docs have a page specifically for using it with Next.

The installation command shows the npm -D command, which is a shorthand for npm --save-dev to install the packages as dev dependencies. However, since I'm using yarn, I'll run:

yarn add --dev tailwindcss@latest postcss@latest autoprefixer@latest

Then we have to initialize Tailwind by running npx tailwindcss init -p.

Configure Unused CSS Purging

By default, Tailwind will ship with all of the CSS. We can configure a PostCSS plugin to purge everything we aren't using.

// Inside of tailwind.config.js
module.exports = {
  purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
}

Add Tailwind to the project

Inside of pages/_app.js import Tailwind CSS into the project:

import "tailwindcss/tailwind.css"

Note that the Tailwind docs offer a different set of installation instructions if you are going to be writing a lot of custom CSS, but for this project I will not be.

Run Next.js in Development Mode

With everything set up, you should now be able to run npm run dev and see our "Home Page" placeholder message in a font that is not the default Times New Roman.