Unverified Commit 389c77f2 authored by C. Lewis's avatar C. Lewis Committed by GitHub

feat(create-next-app): JS/TS prompt (with appDir support); enhanced testing (#42012)

Resubmitting this PR following this comment from Tim. This work has been done already and we can build off of it to get this in faster. 

> Just to be clear we're planning to rework create-next-app to give you the option to choose between JavaScript or TypeScript so it'll solve this request. For `app` right now it'll stay TypeScript till that is implemented.
> 
> _Originally posted by @timneutkens in https://github.com/vercel/next.js/discussions/41745#discussioncomment-3985833_

---

I added the `--ts, --typescript` flag to `create-next-app` in https://github.com/vercel/next.js/pull/24655, and since then I have seen it used very frequently, including in recent issues (such as https://github.com/vercel/next.js/issues/33314) and most Next.js tutorials on YouTube. I noticed the template logic added in this PR was also used to add the `appDir` configuration as well.

We discussed a while ago adding the following user flow:

- `create-next-app --js, --javascript` creates a JS project
- `create-next-app --ts, --typescript` creates a TS project
- `create-next-app [name]` (no `--js, --ts`) prompts the user to choose either JS or TS, with TS selected by default.

### Review

Adding support for appDir and refactoring the templates brought the pain-of-review up a bit, but it's not so bad when broken into increments.

The original 8-file diff is here:
https://github.com/ctjlewis/next.js/commit/1f47d9b0bf5b2c59dce893ca6634c1a9bfd3dd19

And the PR that brought the diff up to 59 files (mostly owed to `app` template dirs and file structure refactors):
https://github.com/ctjlewis/next.js/commit/bd3ae4afd31f787dd41df2c6ab2e8145deef2138 ([PR link](https://github.com/ctjlewis/next.js/pull/3/files))

### Demo

https://user-images.githubusercontent.com/1657236/198586216-4691ff4c-48d4-4c6c-b7c1-705c38dd0194.movCo-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent b7a9b062
......@@ -6,6 +6,10 @@ description: Create Next.js apps in one command with create-next-app.
The easiest way to get started with Next.js is by using `create-next-app`. This CLI tool enables you to quickly start building a new Next.js application, with everything set up for you. You can create a new app using the default Next.js template, or by using one of the [official Next.js examples](https://github.com/vercel/next.js/tree/canary/examples). To get started, use the following command:
### Interactive
You can create a new project interactively by running:
```bash
npx create-next-app@latest
# or
......@@ -14,27 +18,54 @@ yarn create next-app
pnpm create next-app
```
You can create a [TypeScript project](https://github.com/vercel/next.js/blob/canary/docs/basic-features/typescript.md) with the `--ts, --typescript` flag:
You will be asked for the name of your project, and then whether you want to
create a TypeScript project:
```bash
npx create-next-app@latest --ts
# or
yarn create next-app --typescript
# or
pnpm create next-app --ts
✔ Would you like to use TypeScript with this project? … No / Yes
```
### Options
Select **Yes** to install the necessary types/dependencies and create a new TS project.
### Non-interactive
You can also pass command line arguments to set up a new project
non-interactively. See `create-next-app --help`:
```bash
create-next-app <project-directory> [options]
Options:
-V, --version output the version number
--ts, --typescript
`create-next-app` comes with the following options:
Initialize as a TypeScript project. (default)
- **--ts, --typescript** - Initialize as a TypeScript project.
- **-e, --example [name]|[github-url]** - An example to bootstrap the app with. You can use an example name from the [Next.js repo](https://github.com/vercel/next.js/tree/canary/examples) or a GitHub URL. The URL can use any branch and/or subdirectory.
- **--example-path [path-to-example]** - In a rare case, your GitHub URL might contain a branch name with a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar). In this case, you must specify the path to the example separately: `--example-path foo/bar`
- **--use-npm** - Explicitly tell the CLI to bootstrap the app using npm
- **--use-pnpm** - Explicitly tell the CLI to bootstrap the app using pnpm
--js, --javascript
Note: To bootstrap using `yarn` we recommend running `yarn create next-app`
Initialize as a JavaScript project.
--use-npm
Explicitly tell the CLI to bootstrap the app using npm
--use-pnpm
Explicitly tell the CLI to bootstrap the app using pnpm
-e, --example [name]|[github-url]
An example to bootstrap the app with. You can use an example name
from the official Next.js repo or a GitHub URL. The URL can use
any branch and/or subdirectory
--example-path <path-to-example>
In a rare case, your GitHub URL might contain a branch name with
a slash (e.g. bug/fix-1) and the path to the example (e.g. foo/bar).
In this case, you must specify the path to the example separately:
--example-path foo/bar
```
### Why use Create Next App?
......
/* eslint-disable import/no-extraneous-dependencies */
import retry from 'async-retry'
import chalk from 'chalk'
import cpy from 'cpy'
import fs from 'fs'
import os from 'os'
import path from 'path'
import {
downloadAndExtractExample,
......@@ -21,6 +19,13 @@ 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({
......@@ -39,11 +44,8 @@ export async function createApp({
experimentalApp: boolean
}): Promise<void> {
let repoInfo: RepoInfo | undefined
const template = experimentalApp
? 'experimental-app'
: typescript
? 'typescript'
: 'default'
const mode: TemplateMode = typescript ? 'ts' : 'js'
const template: TemplateType = experimentalApp ? 'app' : 'default'
if (example) {
let repoUrl: URL | undefined
......@@ -176,20 +178,20 @@ export async function createApp({
isErrorLike(reason) ? reason.message : reason + ''
)
}
// Copy our default `.gitignore` if the application did not provide one
// Copy `.gitignore` if the application did not provide one
const ignorePath = path.join(root, '.gitignore')
if (!fs.existsSync(ignorePath)) {
fs.copyFileSync(
path.join(__dirname, 'templates', template, 'gitignore'),
getTemplateFile({ template, mode, file: 'gitignore' }),
ignorePath
)
}
// Copy default `next-env.d.ts` to any example that is typescript
// Copy `next-env.d.ts` to any example that is typescript
const tsconfigPath = path.join(root, 'tsconfig.json')
if (fs.existsSync(tsconfigPath)) {
fs.copyFileSync(
path.join(__dirname, 'templates', 'typescript', 'next-env.d.ts'),
getTemplateFile({ template, mode: 'ts', file: 'next-env.d.ts' }),
path.join(root, 'next-env.d.ts')
)
}
......@@ -204,104 +206,16 @@ export async function createApp({
}
} else {
/**
* Otherwise, if an example repository is not provided for cloning, proceed
* If an example repository is not provided for cloning, proceed
* by installing from a template.
*/
console.log(chalk.bold(`Using ${packageManager}.`))
/**
* Create a package.json for the new project.
*/
const packageJson = {
name: appName,
version: '0.1.0',
private: true,
scripts: {
dev: 'next dev',
build: 'next build',
start: 'next start',
lint: 'next lint',
},
}
/**
* Write it to disk.
*/
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2) + os.EOL
)
/**
* These flags will be passed to `install()`.
*/
const installFlags = { packageManager, isOnline }
/**
* Default dependencies.
*/
const dependencies = ['react', 'react-dom', 'next']
/**
* Default devDependencies.
*/
const devDependencies = ['eslint', 'eslint-config-next']
/**
* TypeScript projects will have type definitions and other devDependencies.
*/
if (template !== 'default') {
devDependencies.push(
'typescript',
'@types/react',
'@types/node',
'@types/react-dom'
)
}
/**
* Install package.json dependencies if they exist.
*/
if (dependencies.length) {
console.log()
console.log('Installing dependencies:')
for (const dependency of dependencies) {
console.log(`- ${chalk.cyan(dependency)}`)
}
console.log()
await install(root, dependencies, installFlags)
}
/**
* Install package.json devDependencies if they exist.
*/
if (devDependencies.length) {
console.log()
console.log('Installing devDependencies:')
for (const devDependency of devDependencies) {
console.log(`- ${chalk.cyan(devDependency)}`)
}
console.log()
const devInstallFlags = { devDependencies: true, ...installFlags }
await install(root, devDependencies, devInstallFlags)
}
console.log('\nInitializing project with template: ', template, '\n')
/**
* Copy the template files to the target directory.
*/
await cpy('**', root, {
parents: true,
cwd: path.join(__dirname, 'templates', template),
rename: (name) => {
switch (name) {
case 'gitignore':
case 'eslintrc.json': {
return '.'.concat(name)
}
// README.md is ignored by webpack-asset-relocator-loader used by ncc:
// https://github.com/vercel/webpack-asset-relocator-loader/blob/e9308683d47ff507253e37c9bcbb99474603192b/src/asset-relocator.js#L227
case 'README-template.md': {
return 'README.md'
}
default: {
return name
}
}
},
await installTemplate({
appName,
root,
template,
mode,
packageManager,
isOnline,
})
}
......
......@@ -9,6 +9,7 @@ import { createApp, DownloadError } from './create-app'
import { getPkgManager } from './helpers/get-pkg-manager'
import { validateNpmName } from './helpers/validate-pkg'
import packageJson from './package.json'
import ciInfo from 'ci-info'
let projectPath: string = ''
......@@ -23,7 +24,14 @@ const program = new Commander.Command(packageJson.name)
'--ts, --typescript',
`
Initialize as a TypeScript project.
Initialize as a TypeScript project. (default)
`
)
.option(
'--js, --javascript',
`
Initialize as a JavaScript project.
`
)
.option(
......@@ -136,6 +144,50 @@ async function run(): Promise<void> {
}
const example = typeof program.example === 'string' && program.example.trim()
/**
* If the user does not provide the necessary flags, prompt them for whether
* to use TS or JS.
*
* @todo Allow appDir to support TS or JS, currently TS-only and disables all
* --ts, --js features.
*/
if (!example && !program.typescript && !program.javascript) {
if (ciInfo.isCI) {
// default to JavaScript in CI as we can't prompt to
// prevent breaking setup flows
program.javascript = true
program.typescript = false
} else {
const styledTypeScript = chalk.hex('#007acc')('TypeScript')
const { typescript } = await prompts(
{
type: 'toggle',
name: 'typescript',
message: `Would you like to use ${styledTypeScript} with this project?`,
initial: true,
active: 'Yes',
inactive: 'No',
},
{
/**
* User inputs Ctrl+C or Ctrl+D to exit the prompt. We should close the
* process and not write to the file system.
*/
onCancel: () => {
console.error('Exiting.')
process.exit(1)
},
}
)
/**
* Depending on the prompt response, set the appropriate program flags.
*/
program.typescript = Boolean(typescript)
program.javascript = !Boolean(typescript)
}
}
try {
await createApp({
appPath: resolvedProjectPath,
......
......@@ -30,6 +30,7 @@
"devDependencies": {
"@types/async-retry": "1.4.2",
"@types/cross-spawn": "6.0.0",
"@types/ci-info": "2.0.0",
"@types/node": "^12.6.8",
"@types/prompts": "2.0.1",
"@types/rimraf": "3.0.0",
......@@ -38,6 +39,7 @@
"@vercel/ncc": "0.34.0",
"async-retry": "1.3.1",
"chalk": "2.4.2",
"ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
"commander": "2.20.0",
"cpy": "7.3.0",
"cross-spawn": "6.0.5",
......
import './globals.css'
export default function RootLayout({ children }) {
return (
<html lang="en">
<head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</head>
<body>{children}</body>
</html>
)
}
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction}
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.
The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
.container {
padding: 0 2rem;
}
.main {
min-height: 100vh;
padding: 4rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.footer {
display: flex;
flex: 1;
padding: 2rem 0;
border-top: 1px solid #eaeaea;
justify-content: center;
align-items: center;
}
.footer a {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
}
.title {
margin: 0;
line-height: 1.15;
font-size: 4rem;
font-style: normal;
font-weight: 800;
letter-spacing: -0.025em;
}
.title a {
text-decoration: none;
color: #0070f3;
}
.title a:hover,
.title a:focus,
.title a:active {
text-decoration: underline;
}
.title,
.description {
text-align: center;
}
.description {
margin: 4rem 0;
line-height: 1.5;
font-size: 1.5rem;
}
.code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
.grid {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 1200px;
}
.card {
margin: 1rem;
padding: 1.5rem;
text-align: left;
color: inherit;
text-decoration: none;
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.15s ease, border-color 0.15s ease;
max-width: 300px;
}
.card:hover,
.card:focus,
.card:active {
color: #0070f3;
border-color: #0070f3;
}
.card h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
.card p {
margin: 0;
font-size: 1.25rem;
line-height: 1.5;
}
.logo {
height: 1em;
margin-left: 0.5rem;
}
@media (max-width: 600px) {
.grid {
width: 100%;
flex-direction: column;
}
}
@media (prefers-color-scheme: dark) {
.title {
background: linear-gradient(180deg, #ffffff 0%, #aaaaaa 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
text-fill-color: transparent;
}
.title a {
background: linear-gradient(180deg, #0070f3 0%, #0153af 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
text-fill-color: transparent;
}
.card,
.footer {
border-color: #222;
}
.code {
background: #111;
}
.logo img {
filter: invert(1);
}
}
import Image from 'next/image'
import styles from './page.module.css'
export default function Home() {
return (
<div className={styles.container}>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js 13!</a>
</h1>
<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>app/page.tsx</code>
</p>
<div className={styles.grid}>
<a href="https://beta.nextjs.org/docs" className={styles.card}>
<h2>Documentation &rarr;</h2>
<p>Find in-depth information about Next.js 13</p>
</a>
<a
href="https://github.com/vercel/next.js/tree/canary/examples"
className={styles.card}
>
<h2>Examples &rarr;</h2>
<p>Explore the Next.js 13 playground.</p>
</a>
<a
href="https://vercel.com/templates/next.js/app-directory?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
className={styles.card}
>
<h2>Deploy &rarr;</h2>
<p>Deploy your Next.js site to a public URL with Vercel.</p>
</a>
</div>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
</div>
)
}
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
},
}
module.exports = nextConfig
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>
\ No newline at end of file
html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
body {
color: white;
background: black;
}
}
import { install } from '../helpers/install'
import cpy from 'cpy'
import os from 'os'
import fs from 'fs'
import path from 'path'
import chalk from 'chalk'
import { GetTemplateFileArgs, InstallTemplateArgs } from './types'
/**
* Get the file path for a given file in a template, e.g. "next.config.js".
*/
export const getTemplateFile = ({
template,
mode,
file,
}: GetTemplateFileArgs): string => {
return path.join(__dirname, template, mode, file)
}
/**
* Install a Next.js internal template to a given `root` directory.
*/
export const installTemplate = async ({
appName,
root,
packageManager,
isOnline,
template,
mode,
}: InstallTemplateArgs) => {
console.log(chalk.bold(`Using ${packageManager}.`))
/**
* Create a package.json for the new project.
*/
const packageJson = {
name: appName,
version: '0.1.0',
private: true,
scripts: {
dev: 'next dev',
build: 'next build',
start: 'next start',
lint: 'next lint',
},
}
/**
* Write it to disk.
*/
fs.writeFileSync(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2) + os.EOL
)
/**
* These flags will be passed to `install()`, which calls the package manager
* install process.
*/
const installFlags = { packageManager, isOnline }
/**
* Default dependencies.
*/
const dependencies = ['react', 'react-dom', 'next']
/**
* Default devDependencies.
*/
const devDependencies = ['eslint', 'eslint-config-next']
/**
* TypeScript projects will have type definitions and other devDependencies.
*/
if (mode === 'ts') {
devDependencies.push(
'typescript',
'@types/react',
'@types/node',
'@types/react-dom'
)
}
/**
* Install package.json dependencies if they exist.
*/
if (dependencies.length) {
console.log()
console.log('Installing dependencies:')
for (const dependency of dependencies) {
console.log(`- ${chalk.cyan(dependency)}`)
}
console.log()
await install(root, dependencies, installFlags)
}
/**
* Install package.json devDependencies if they exist.
*/
if (devDependencies.length) {
console.log()
console.log('Installing devDependencies:')
for (const devDependency of devDependencies) {
console.log(`- ${chalk.cyan(devDependency)}`)
}
console.log()
const devInstallFlags = { devDependencies: true, ...installFlags }
await install(root, devDependencies, devInstallFlags)
}
/**
* Copy the template files to the target directory.
*/
console.log('\nInitializing project with template: ', template, '\n')
const templatePath = path.join(__dirname, template, mode)
await cpy('**', root, {
parents: true,
cwd: templatePath,
rename: (name) => {
switch (name) {
case 'gitignore':
case 'eslintrc.json': {
return '.'.concat(name)
}
// README.md is ignored by webpack-asset-relocator-loader used by ncc:
// https://github.com/vercel/webpack-asset-relocator-loader/blob/e9308683d47ff507253e37c9bcbb99474603192b/src/asset-relocator.js#L227
case 'README-template.md': {
return 'README.md'
}
default: {
return name
}
}
},
})
}
export * from './types'
import { PackageManager } from '../helpers/get-pkg-manager'
export type TemplateType = 'default' | 'app'
export type TemplateMode = 'js' | 'ts'
export interface GetTemplateFileArgs {
template: TemplateType
mode: TemplateMode
file: string
}
export interface InstallTemplateArgs {
appName: string
root: string
packageManager: PackageManager
isOnline: boolean
template: TemplateType
mode: TemplateMode
}
......@@ -360,6 +360,7 @@ importers:
packages/create-next-app:
specifiers:
'@types/async-retry': 1.4.2
'@types/ci-info': 2.0.0
'@types/cross-spawn': 6.0.0
'@types/node': ^12.6.8
'@types/prompts': 2.0.1
......@@ -369,6 +370,7 @@ importers:
'@vercel/ncc': 0.34.0
async-retry: 1.3.1
chalk: 2.4.2
ci-info: watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540
commander: 2.20.0
cpy: 7.3.0
cross-spawn: 6.0.5
......@@ -380,6 +382,7 @@ importers:
validate-npm-package-name: 3.0.0
devDependencies:
'@types/async-retry': 1.4.2
'@types/ci-info': 2.0.0
'@types/cross-spawn': 6.0.0
'@types/node': 12.12.24
'@types/prompts': 2.0.1
......@@ -389,6 +392,7 @@ importers:
'@vercel/ncc': 0.34.0
async-retry: 1.3.1
chalk: 2.4.2
ci-info: github.com/watson/ci-info/f43f6a1cefff47fb361c88cf4b943fdbcaafe540
commander: 2.20.0
cpy: 7.3.0
cross-spawn: 6.0.5
......
import {
TemplateMode,
TemplateType,
} from '../../../../packages/create-next-app/templates'
export type ProjectSettings = {
files: string[]
deps: string[]
devDeps: string[]
}
export type ProjectSpecification = {
global: ProjectSettings
} & {
[key in TemplateType]: {
[key in TemplateMode]: ProjectSettings
}
}
/**
* Required files for a given project template and mode.
*/
export const projectSpecification: ProjectSpecification = {
global: {
files: [
'package.json',
'.eslintrc.json',
'node_modules/next',
'.gitignore',
],
deps: ['next', 'react', 'react-dom'],
devDeps: ['eslint', 'eslint-config-next'],
},
default: {
js: {
files: ['pages/index.js', 'pages/_app.js', 'pages/api/hello.js'],
deps: [],
devDeps: [],
},
ts: {
files: [
'pages/index.tsx',
'pages/_app.tsx',
'pages/api/hello.ts',
'tsconfig.json',
'next-env.d.ts',
],
deps: [],
devDeps: [
'@types/node',
'@types/react',
'@types/react-dom',
'typescript',
],
},
},
app: {
js: {
deps: [],
devDeps: [],
files: ['app/page.jsx', 'app/layout.jsx', 'pages/api/hello.js'],
},
ts: {
deps: [],
devDeps: [
'@types/node',
'@types/react',
'@types/react-dom',
'typescript',
],
files: [
'app/page.tsx',
'app/layout.tsx',
'pages/api/hello.ts',
'tsconfig.json',
'next-env.d.ts',
],
},
},
}
export type GetProjectSettingsArgs = {
template: TemplateType
mode: TemplateMode
setting: keyof ProjectSettings
}
export const getProjectSetting = ({
template,
mode,
setting,
}: GetProjectSettingsArgs) => {
return [
...projectSpecification.global[setting],
...projectSpecification[template][mode][setting],
]
}
import {
TemplateMode,
TemplateType,
} from '../../../../packages/create-next-app/templates'
export interface DefaultTemplateOptions {
cwd: string
projectName: string
}
export interface CustomTemplateOptions extends DefaultTemplateOptions {
mode: TemplateMode
template: TemplateType
}
export interface ProjectFiles extends DefaultTemplateOptions {
files: string[]
}
export interface ProjectDeps extends DefaultTemplateOptions {
type: 'dependencies' | 'devDependencies'
deps: string[]
}
/**
* @fileoverview
*
* This file contains utilities for `create-next-app` testing.
*/
import { ChildProcess, spawn, SpawnOptions } from 'child_process'
import { existsSync } from 'fs'
import { resolve } from 'path'
import { getProjectSetting, projectSpecification } from './specification'
import { CustomTemplateOptions, ProjectDeps, ProjectFiles } from './types'
const cli = require.resolve('create-next-app/dist/index.js')
/**
* Run the built version of `create-next-app` with the given arguments.
*/
export const createNextApp = (args: string[], options?: SpawnOptions) => {
console.log(`[TEST] $ ${cli} ${args.join(' ')}`, { options })
return spawn('node', [cli].concat(args), options ?? {})
}
/**
* Return a Promise that resolves when the process exits with code 0 and rejects
* otherwise.
*/
export const spawnExitPromise = (childProcess: ChildProcess) => {
return new Promise((resolve, reject) => {
childProcess
.on('exit', (code) => {
if (code === 0) {
resolve(code)
} else {
reject(code)
}
})
.on('error', reject)
})
}
export const projectFilesShouldExist = ({
cwd,
projectName,
files,
}: ProjectFiles) => {
const projectRoot = resolve(cwd, projectName)
for (const file of files) {
expect(existsSync(resolve(projectRoot, file))).toBe(true)
}
}
export const projectFilesShouldNotExist = ({
cwd,
projectName,
files,
}: ProjectFiles) => {
const projectRoot = resolve(cwd, projectName)
for (const file of files) {
expect(existsSync(resolve(projectRoot, file))).toBe(false)
}
}
export const projectDepsShouldBe = ({
cwd,
projectName,
type,
deps,
}: ProjectDeps) => {
const projectRoot = resolve(cwd, projectName)
const pkgJson = require(resolve(projectRoot, 'package.json'))
expect(Object.keys(pkgJson[type]).sort()).toEqual(deps.sort())
}
export const shouldBeTemplateProject = ({
cwd,
projectName,
template,
mode,
}: CustomTemplateOptions) => {
projectFilesShouldExist({
cwd,
projectName,
files: getProjectSetting({ template, mode, setting: 'files' }),
})
projectFilesShouldNotExist({
cwd,
projectName,
files: projectSpecification[template][mode === 'js' ? 'ts' : 'js'].files,
})
projectDepsShouldBe({
type: 'dependencies',
cwd,
projectName,
deps: getProjectSetting({ template, mode, setting: 'deps' }),
})
projectDepsShouldBe({
type: 'devDependencies',
cwd,
projectName,
deps: getProjectSetting({ template, mode, setting: 'devDeps' }),
})
}
export const shouldBeJavascriptProject = ({
cwd,
projectName,
template,
}: Omit<CustomTemplateOptions, 'mode'>) => {
shouldBeTemplateProject({ cwd, projectName, template, mode: 'js' })
}
export const shouldBeTypescriptProject = ({
cwd,
projectName,
template,
}: Omit<CustomTemplateOptions, 'mode'>) => {
shouldBeTemplateProject({ cwd, projectName, template, mode: 'ts' })
}
/* eslint-env jest */
/**
* @fileoverview
*
* This file contains tests for `create-next-app` templates, currently
* JavaScript (default), TypeScript, and appDir.
*/
import {
createNextApp,
projectFilesShouldNotExist,
shouldBeJavascriptProject,
shouldBeTemplateProject,
shouldBeTypescriptProject,
spawnExitPromise,
} from './lib/utils'
import { useTempDir } from '../../../test/lib/use-temp-dir'
describe('create-next-app templates', () => {
it('should prompt user to choose if --ts or --js is not provided', async () => {
useTempDir(async (cwd) => {
const projectName = 'choose-ts-js'
/**
* Start the create-next-app call.
*/
const childProcess = createNextApp([projectName], { cwd })
/**
* Wait for the prompt to display.
*/
// await new Promise((resolve) => setTimeout(resolve, 1000));
/**
* Bind the exit listener.
*/
childProcess.on('exit', (exitCode) => {
expect(exitCode).toBe(0)
/**
* Verify it correctly emitted a TS project by looking for tsconfig.
*/
projectFilesShouldNotExist({
cwd,
projectName,
files: ['tsconfig.json'],
})
})
/**
* Simulate "Y" for TypeScript.
*/
childProcess.stdin.write('N\n')
})
})
it('should create TS projects with --ts, --typescript', async () => {
await useTempDir(async (cwd) => {
const projectName = 'typescript-test'
const childProcess = createNextApp([projectName, '--ts'], { cwd })
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeTypescriptProject({ cwd, projectName, template: 'default' })
})
})
it('should create JS projects with --js, --javascript', async () => {
await useTempDir(async (cwd) => {
const projectName = 'javascript-test'
const childProcess = createNextApp([projectName, '--js'], { cwd })
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeJavascriptProject({ cwd, projectName, template: 'default' })
})
})
})
describe('create-next-app --experimental-app-dir', () => {
it('should create TS appDir projects with --ts', async () => {
await useTempDir(async (cwd) => {
const projectName = 'appdir-test'
const childProcess = createNextApp(
[projectName, '--ts', '--experimental-app'],
{
cwd,
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeTemplateProject({ cwd, projectName, template: 'app', mode: 'ts' })
})
})
it('should create JS appDir projects with --js', async () => {
await useTempDir(async (cwd) => {
const projectName = 'appdir-test'
const childProcess = createNextApp(
[projectName, '--js', '--experimental-app'],
{
cwd,
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeTemplateProject({ cwd, projectName, template: 'app', mode: 'js' })
})
})
})
import fs from 'fs-extra'
import os from 'os'
import path from 'path'
/**
* Create a randomly-named directory in `os.tmpdir()`, await a function call,
* and delete the directory when finished.
*/
export async function useTempDir(
fn: (folder: string) => void | Promise<void>,
mode?: string | number
) {
const folder = path.join(os.tmpdir(), Math.random().toString(36).slice(2))
await fs.mkdirp(folder)
if (mode) {
fs.chmod(folder, mode)
}
try {
await fn(folder)
} finally {
await fs.remove(folder)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment