rsnext/packages/create-next-app/create-app.ts
Balázs Orbán 8c98a207f2
feat(cli): introduce --tailwind flag (#46927)
### What?

This PR introduces a new `--tailwind` flag to the `create-next-app` CLI,
to make it easier to bootstrap a Next.js app with Tailwind CSS
pre-configured. This is going to be the **default**. To opt-out of
Tailwind CSS, you can use the `--no-tailwind` flag.

### Why?

Tailwind CSS is one of the most popular styling solutions right now, and
we would like to make it easier to get started.

Currently, the closest you can come to this is by running `pnpm create
next-app -e with-tailwindcss` which will clone the
https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss
example. But that example is not configured for the App Router. This PR
will let you add Tailwind CSS to both `app/`, `pages/`, and start out
with TypeScript or JavaScript via the CLI prompts.

(Some community feedback
https://twitter.com/dev_jonaskaas/status/1632367991827443713,
https://twitter.com/samselikoff/status/1634662473331617794)

### How?

We are adding 4 new templates to the CLI bundle.

> Note: The styling is not pixel-perfect compared to the current
templates (using CSS modules) to require fewer overrides, but I tried to
match it as close as possible. Here are a few screenshots:

<details>
<summary><b>Current, light</b></summary>
<img
src="https://user-images.githubusercontent.com/18369201/224733372-9dba86fe-9191-471d-ad9f-ab904c47f544.png"/>
</details>

<details>
<summary><b>Tailwind (new), light</b></summary>
<img
src="https://user-images.githubusercontent.com/18369201/224733610-038d9d0f-634d-4b69-b5c2-a5056b56760c.png"/>
</details>

<details>
<summary><b>Current, dark, responsive</b></summary>
<img
src="https://user-images.githubusercontent.com/18369201/224733790-9b4d730c-0336-4dbe-bc10-1cae1d7fd145.png"/>
</details>

<details>
<summary><b>Tailwind (new), dark, responsive</b></summary>
<img
src="https://user-images.githubusercontent.com/18369201/224734375-28384bbc-2c3a-4125-8f29-c102f3b7aa1d.png"/>
</details>

#### For reviewers

This introduces 4 new templates, with a very similar code base to the
original ones. To keep the PR focused, I decided to copy over duplicate
code, but we could potentially create a shared folder for files that are
the same across templates to somewhat reduce the CLI size. Not sure if
it's worth it, let me know. Probably fine for now, but something to
consider if we are adding more permutations in the future.

---

~Work remaining:~

- [x] app+ts
	- [x] layout
	- [x] dark mode
	- [x] media queries
	- [x] animations
- [x] app+js
- [x] pages+ts
- [x] pages+js
- [x] prompt/config
- [x] deprecate Tailwind CSS example in favor of CLI
- [x] update docs
- [x] add test
- [x] add [Prettier
plugin](https://github.com/tailwindlabs/prettier-plugin-tailwindcss)
 
Closes NEXT-772
Related #45814, #44286
2023-03-16 16:06:27 +01:00

274 lines
7.1 KiB
TypeScript

/* eslint-disable import/no-extraneous-dependencies */
import retry from 'async-retry'
import chalk from 'chalk'
import fs from 'fs'
import path from 'path'
import {
downloadAndExtractExample,
downloadAndExtractRepo,
getRepoInfo,
existsInRepo,
hasRepo,
RepoInfo,
} from './helpers/examples'
import { makeDir } from './helpers/make-dir'
import { tryGitInit } from './helpers/git'
import { install } from './helpers/install'
import { isFolderEmpty } from './helpers/is-folder-empty'
import { getOnline } from './helpers/is-online'
import { isWriteable } from './helpers/is-writeable'
import type { PackageManager } from './helpers/get-pkg-manager'
import {
getTemplateFile,
installTemplate,
TemplateMode,
TemplateType,
} from './templates'
export class DownloadError extends Error {}
export async function createApp({
appPath,
packageManager,
example,
examplePath,
typescript,
tailwind,
eslint,
experimentalApp,
srcDir,
importAlias,
}: {
appPath: string
packageManager: PackageManager
example?: string
examplePath?: string
typescript: boolean
tailwind: boolean
eslint: boolean
experimentalApp: boolean
srcDir: boolean
importAlias: string
}): Promise<void> {
let repoInfo: RepoInfo | undefined
const mode: TemplateMode = typescript ? 'ts' : 'js'
const template: TemplateType = experimentalApp
? tailwind
? 'app-tw'
: 'app'
: tailwind
? 'default-tw'
: 'default'
if (example) {
let repoUrl: URL | undefined
try {
repoUrl = new URL(example)
} catch (error: any) {
if (error.code !== 'ERR_INVALID_URL') {
console.error(error)
process.exit(1)
}
}
if (repoUrl) {
if (repoUrl.origin !== 'https://github.com') {
console.error(
`Invalid URL: ${chalk.red(
`"${example}"`
)}. Only GitHub repositories are supported. Please use a GitHub URL and try again.`
)
process.exit(1)
}
repoInfo = await getRepoInfo(repoUrl, examplePath)
if (!repoInfo) {
console.error(
`Found invalid GitHub URL: ${chalk.red(
`"${example}"`
)}. Please fix the URL and try again.`
)
process.exit(1)
}
const found = await hasRepo(repoInfo)
if (!found) {
console.error(
`Could not locate the repository for ${chalk.red(
`"${example}"`
)}. Please check that the repository exists and try again.`
)
process.exit(1)
}
} else if (example !== '__internal-testing-retry') {
const found = await existsInRepo(example)
if (!found) {
console.error(
`Could not locate an example named ${chalk.red(
`"${example}"`
)}. It could be due to the following:\n`,
`1. Your spelling of example ${chalk.red(
`"${example}"`
)} might be incorrect.\n`,
`2. You might not be connected to the internet or you are behind a proxy.`
)
process.exit(1)
}
}
}
const root = path.resolve(appPath)
if (!(await isWriteable(path.dirname(root)))) {
console.error(
'The application path is not writable, please check folder permissions and try again.'
)
console.error(
'It is likely you do not have write permissions for this folder.'
)
process.exit(1)
}
const appName = path.basename(root)
await makeDir(root)
if (!isFolderEmpty(root, appName)) {
process.exit(1)
}
const useYarn = packageManager === 'yarn'
const isOnline = !useYarn || (await getOnline())
const originalDirectory = process.cwd()
console.log(`Creating a new Next.js app in ${chalk.green(root)}.`)
console.log()
process.chdir(root)
const packageJsonPath = path.join(root, 'package.json')
let hasPackageJson = false
if (example) {
/**
* If an example repository is provided, clone it.
*/
try {
if (repoInfo) {
const repoInfo2 = repoInfo
console.log(
`Downloading files from repo ${chalk.cyan(
example
)}. This might take a moment.`
)
console.log()
await retry(() => downloadAndExtractRepo(root, repoInfo2), {
retries: 3,
})
} else {
console.log(
`Downloading files for example ${chalk.cyan(
example
)}. This might take a moment.`
)
console.log()
await retry(() => downloadAndExtractExample(root, example), {
retries: 3,
})
}
} catch (reason) {
function isErrorLike(err: unknown): err is { message: string } {
return (
typeof err === 'object' &&
err !== null &&
typeof (err as { message?: unknown }).message === 'string'
)
}
throw new DownloadError(
isErrorLike(reason) ? reason.message : reason + ''
)
}
// Copy `.gitignore` if the application did not provide one
const ignorePath = path.join(root, '.gitignore')
if (!fs.existsSync(ignorePath)) {
fs.copyFileSync(
getTemplateFile({ template, mode, file: 'gitignore' }),
ignorePath
)
}
// Copy `next-env.d.ts` to any example that is typescript
const tsconfigPath = path.join(root, 'tsconfig.json')
if (fs.existsSync(tsconfigPath)) {
fs.copyFileSync(
getTemplateFile({ template, mode: 'ts', file: 'next-env.d.ts' }),
path.join(root, 'next-env.d.ts')
)
}
hasPackageJson = fs.existsSync(packageJsonPath)
if (hasPackageJson) {
console.log('Installing packages. This might take a couple of minutes.')
console.log()
await install(root, null, { packageManager, isOnline })
console.log()
}
} else {
/**
* If an example repository is not provided for cloning, proceed
* by installing from a template.
*/
await installTemplate({
appName,
root,
template,
mode,
packageManager,
isOnline,
tailwind,
eslint,
srcDir,
importAlias,
})
}
if (tryGitInit(root)) {
console.log('Initialized a git repository.')
console.log()
}
let cdpath: string
if (path.join(originalDirectory, appName) === appPath) {
cdpath = appName
} else {
cdpath = appPath
}
console.log(`${chalk.green('Success!')} Created ${appName} at ${appPath}`)
if (hasPackageJson) {
console.log('Inside that directory, you can run several commands:')
console.log()
console.log(chalk.cyan(` ${packageManager} ${useYarn ? '' : 'run '}dev`))
console.log(' Starts the development server.')
console.log()
console.log(chalk.cyan(` ${packageManager} ${useYarn ? '' : 'run '}build`))
console.log(' Builds the app for production.')
console.log()
console.log(chalk.cyan(` ${packageManager} start`))
console.log(' Runs the built app in production mode.')
console.log()
console.log('We suggest that you begin by typing:')
console.log()
console.log(chalk.cyan(' cd'), cdpath)
console.log(
` ${chalk.cyan(`${packageManager} ${useYarn ? '' : 'run '}dev`)}`
)
}
console.log()
}