Unverified Commit 89332890 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update prompts for CNA and add default @/* alias (#44672)

This adds prompts for using a `src/` directory and experimental `app/`
directory with create-next-app. Also adds `jsconfig` and `tsconfig`
options to alias `@/*` by default.

x-ref: [slack
thread](https://vercel.slack.com/archives/C03KAR5DCKC/p1672856097701429)


## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [x] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)
parent f4d9a50a
......@@ -33,7 +33,7 @@ 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]
Usage: create-next-app <project-directory> [options]
Options:
-V, --version output the version number
......@@ -49,14 +49,14 @@ Options:
Initialize with eslint config.
--no-eslint
Initialize without eslint config.
--experimental-app
Initialize as a `app/` directory project.
--src-dir
Initialize inside a `src/` directory.
--use-npm
Explicitly tell the CLI to bootstrap the app using npm
......@@ -77,6 +77,8 @@ Options:
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
-h, --help output usage information
```
### Why use Create Next App?
......
......@@ -36,6 +36,7 @@ export async function createApp({
typescript,
eslint,
experimentalApp,
srcDir,
}: {
appPath: string
packageManager: PackageManager
......@@ -44,6 +45,7 @@ export async function createApp({
typescript: boolean
eslint: boolean
experimentalApp: boolean
srcDir: boolean
}): Promise<void> {
let repoInfo: RepoInfo | undefined
const mode: TemplateMode = typescript ? 'ts' : 'js'
......@@ -219,6 +221,7 @@ export async function createApp({
packageManager,
isOnline,
eslint,
srcDir,
})
}
......
......@@ -46,6 +46,13 @@ const program = new Commander.Command(packageJson.name)
`
Initialize as a \`app/\` directory project.
`
)
.option(
'--src-dir',
`
Initialize inside a \`src/\` directory.
`
)
.option(
......@@ -212,6 +219,48 @@ async function run(): Promise<void> {
program.eslint = Boolean(eslint)
}
}
if (
!process.argv.includes('--src-dir') &&
!process.argv.includes('--no-src-dir')
) {
if (ciInfo.isCI) {
program.srcDir = false
} else {
const styledSrcDir = chalk.hex('#007acc')('`src/` directory')
const { srcDir } = await prompts({
type: 'toggle',
name: 'srcDir',
message: `Would you like to use ${styledSrcDir} with this project?`,
initial: false,
active: 'Yes',
inactive: 'No',
})
program.srcDir = Boolean(srcDir)
}
}
if (
!process.argv.includes('--experimental-app') &&
!process.argv.includes('--no-experimental-app')
) {
if (ciInfo.isCI) {
program.experimentalAll = false
} else {
const styledAppDir = chalk.hex('#007acc')(
'experimental `app/` directory'
)
const { appDir } = await prompts({
type: 'toggle',
name: 'appDir',
message: `Would you like to use ${styledAppDir} with this project?`,
initial: false,
active: 'Yes',
inactive: 'No',
})
program.experimentalApp = Boolean(appDir)
}
}
}
try {
......@@ -223,6 +272,7 @@ async function run(): Promise<void> {
typescript: program.typescript,
eslint: program.eslint,
experimentalApp: program.experimentalApp,
srcDir: program.srcDir,
})
} catch (reason) {
if (!(reason instanceof DownloadError)) {
......@@ -247,6 +297,7 @@ async function run(): Promise<void> {
typescript: program.typescript,
eslint: program.eslint,
experimentalApp: program.experimentalApp,
srcDir: program.srcDir,
})
}
}
......
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
}
......@@ -18,7 +18,11 @@
{
"name": "next"
}
]
],
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
......
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
}
}
import '../styles/globals.css'
import '@/styles/globals.css'
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />
......
import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '../styles/Home.module.css'
import styles from '@/styles/Home.module.css'
const inter = Inter({ subsets: ['latin'] })
......
import '../styles/globals.css'
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
......
import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '../styles/Home.module.css'
import styles from '@/styles/Home.module.css'
const inter = Inter({ subsets: ['latin'] })
......
......@@ -13,7 +13,11 @@
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
"incremental": true,
"baseUrl": ".",
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
......
......@@ -19,6 +19,8 @@ export const getTemplateFile = ({
return path.join(__dirname, template, mode, file)
}
export const SRC_DIR_NAMES = ['app', 'pages', 'styles']
/**
* Install a Next.js internal template to a given `root` directory.
*/
......@@ -30,6 +32,7 @@ export const installTemplate = async ({
template,
mode,
eslint,
srcDir,
}: InstallTemplateArgs) => {
console.log(chalk.bold(`Using ${packageManager}.`))
......@@ -120,6 +123,31 @@ export const installTemplate = async ({
},
})
if (srcDir) {
await fs.promises.mkdir(path.join(root, 'src'), { recursive: true })
await Promise.all(
SRC_DIR_NAMES.map(async (file) => {
await fs.promises
.rename(path.join(root, file), path.join(root, 'src', file))
.catch((err) => {
if (err.code !== 'ENOENT') {
throw err
}
})
})
)
const tsconfigFile = path.join(
root,
mode === 'js' ? 'jsconfig.json' : 'tsconfig.json'
)
await fs.promises.writeFile(
tsconfigFile,
(
await fs.promises.readFile(tsconfigFile, 'utf8')
).replace(`"@/*": ["./*"]`, `"@/*": ["./src/*"]`)
)
}
if (!eslint) {
// remove un-necessary template file if eslint is not desired
await fs.promises.unlink(path.join(root, '.eslintrc.json'))
......
......@@ -18,4 +18,5 @@ export interface InstallTemplateArgs {
template: TemplateType
mode: TemplateMode
eslint: boolean
srcDir: boolean
}
......@@ -29,7 +29,7 @@ const run = (args: string[], options: execa.Options) =>
execa('node', [cli].concat(args), options)
describe('create next app', () => {
if (!process.env.NEXT_TEST_CNA) {
if (!process.env.NEXT_TEST_CNA && process.env.NEXT_TEST_JOB) {
it('should skip when env is not set', () => {})
return
}
......@@ -41,10 +41,19 @@ describe('create next app', () => {
const pkg = path.join(cwd, projectName, 'package.json')
fs.writeFileSync(pkg, '{ "foo": "bar" }')
const res = await run([projectName, '--js', '--eslint'], {
cwd,
reject: false,
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
reject: false,
}
)
expect(res.exitCode).toBe(1)
expect(res.stdout).toMatch(/contains files that could conflict/)
})
......@@ -56,7 +65,16 @@ describe('create next app', () => {
it('empty directory', async () => {
await useTempDir(async (cwd) => {
const projectName = 'empty-directory'
const res = await run([projectName, '--js', '--eslint'], { cwd })
const res = await run(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{ cwd }
)
expect(res.exitCode).toBe(0)
shouldBeJavascriptProject({ cwd, projectName, template: 'default' })
......@@ -294,10 +312,20 @@ describe('create next app', () => {
it('should exit if example flag is empty', async () => {
await useTempDir(async (cwd) => {
const projectName = 'no-example-provided'
const res = await run([projectName, '--js', '--eslint', '--example'], {
cwd,
reject: false,
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--example',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
reject: false,
}
)
expect(res.exitCode).toBe(1)
})
......@@ -320,10 +348,19 @@ describe('create next app', () => {
)
return
}
const res = await run([projectName, '--js', '--eslint'], {
cwd,
reject: false,
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
reject: false,
}
)
expect(res.stderr).toMatch(
/you do not have write permissions for this folder/
......@@ -350,12 +387,15 @@ describe('create next app', () => {
delete env.npm_config_user_agent
}
const res = await run(['.', '--js', '--eslint'], {
cwd,
env,
extendEnv: false,
stdio: 'inherit',
})
const res = await run(
['.', '--js', '--eslint', '--no-src-dir', '--no-experimental-app'],
{
cwd,
env,
extendEnv: false,
stdio: 'inherit',
}
)
await fs.remove(tmpBin)
expect(res.exitCode).toBe(0)
......@@ -366,10 +406,13 @@ describe('create next app', () => {
it('should ask the user for a name for the project if none supplied', async () => {
await useTempDir(async (cwd) => {
const projectName = 'test-project'
const res = await run(['--js', '--eslint'], {
cwd,
input: `${projectName}\n`,
})
const res = await run(
['--js', '--eslint', '--no-src-dir', '--no-experimental-app'],
{
cwd,
input: `${projectName}\n`,
}
)
expect(res.exitCode).toBe(0)
shouldBeJavascriptProject({ cwd, projectName, template: 'default' })
......@@ -379,9 +422,19 @@ describe('create next app', () => {
it('should use npm as the package manager on supplying --use-npm', async () => {
await useTempDir(async (cwd) => {
const projectName = 'use-npm'
const res = await run([projectName, '--js', '--eslint', '--use-npm'], {
cwd,
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--use-npm',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
}
)
expect(res.exitCode).toBe(0)
shouldBeJavascriptProject({ cwd, projectName, template: 'default' })
......@@ -421,9 +474,19 @@ describe('create next app', () => {
it('should use pnpm as the package manager on supplying --use-pnpm', async () => {
await useTempDir(async (cwd) => {
const projectName = 'use-pnpm'
const res = await run([projectName, '--js', '--eslint', '--use-pnpm'], {
cwd,
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--use-pnpm',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
}
)
expect(res.exitCode).toBe(0)
projectFilesShouldExist({
......@@ -481,10 +544,19 @@ describe('create next app', () => {
it('should infer npm as the package manager', async () => {
await useTempDir(async (cwd) => {
const projectName = 'infer-package-manager-npm'
const res = await run([projectName, '--js', '--eslint'], {
cwd,
env: { ...process.env, npm_config_user_agent: 'npm' },
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
env: { ...process.env, npm_config_user_agent: 'npm' },
}
)
const files = [
'package.json',
......@@ -537,10 +609,19 @@ describe('create next app', () => {
await useTempDir(async (cwd) => {
const projectName = 'infer-package-manager-yarn'
const res = await run([projectName, '--js', '--eslint'], {
cwd,
env: { ...process.env, npm_config_user_agent: 'yarn' },
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
env: { ...process.env, npm_config_user_agent: 'yarn' },
}
)
const files = [
'package.json',
......@@ -600,10 +681,19 @@ describe('create next app', () => {
await useTempDir(async (cwd) => {
const projectName = 'infer-package-manager'
const res = await run([projectName, '--js', '--eslint'], {
cwd,
env: { ...process.env, npm_config_user_agent: 'pnpm' },
})
const res = await run(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
env: { ...process.env, npm_config_user_agent: 'pnpm' },
}
)
const files = [
'package.json',
......
import path from 'path'
import {
SRC_DIR_NAMES,
TemplateMode,
TemplateType,
} from '../../../../packages/create-next-app/templates'
......@@ -40,7 +42,12 @@ export const projectSpecification: ProjectSpecification = {
},
default: {
js: {
files: ['pages/index.js', 'pages/_app.js', 'pages/api/hello.js'],
files: [
'pages/index.js',
'pages/_app.js',
'pages/api/hello.js',
'jsconfig.json',
],
deps: [],
devDeps: [],
},
......@@ -65,6 +72,7 @@ export const projectSpecification: ProjectSpecification = {
'app/head.jsx',
'app/layout.jsx',
'pages/api/hello.js',
'jsconfig.json',
],
},
ts: {
......@@ -86,15 +94,24 @@ export type GetProjectSettingsArgs = {
template: TemplateType
mode: TemplateMode
setting: keyof ProjectSettings
srcDir?: boolean
}
export const mapSrcFiles = (files: string[], srcDir?: boolean) =>
files.map((file) =>
srcDir && SRC_DIR_NAMES.some((name) => file.startsWith(name))
? path.join('src', file)
: file
)
export const getProjectSetting = ({
template,
mode,
setting,
srcDir,
}: GetProjectSettingsArgs) => {
return [
...projectSpecification.global[setting],
...projectSpecification[template][mode][setting],
...mapSrcFiles(projectSpecification[template][mode][setting], srcDir),
]
}
......@@ -11,6 +11,7 @@ export interface DefaultTemplateOptions {
export interface CustomTemplateOptions extends DefaultTemplateOptions {
mode: TemplateMode
template: TemplateType
srcDir?: boolean
}
export interface ProjectFiles extends DefaultTemplateOptions {
......
......@@ -9,7 +9,11 @@ import { existsSync } from 'fs'
import { resolve } from 'path'
import glob from 'glob'
import { getProjectSetting, projectSpecification } from './specification'
import {
getProjectSetting,
mapSrcFiles,
projectSpecification,
} from './specification'
import { CustomTemplateOptions, ProjectDeps, ProjectFiles } from './types'
const cli = require.resolve('create-next-app/dist/index.js')
......@@ -110,17 +114,21 @@ export const shouldBeTemplateProject = ({
projectName,
template,
mode,
srcDir,
}: CustomTemplateOptions) => {
projectFilesShouldExist({
cwd,
projectName,
files: getProjectSetting({ template, mode, setting: 'files' }),
files: getProjectSetting({ template, mode, setting: 'files', srcDir }),
})
projectFilesShouldNotExist({
cwd,
projectName,
files: projectSpecification[template][mode === 'js' ? 'ts' : 'js'].files,
files: mapSrcFiles(
projectSpecification[template][mode === 'js' ? 'ts' : 'js'].files,
srcDir
),
})
projectDepsShouldBe({
......@@ -142,14 +150,16 @@ export const shouldBeJavascriptProject = ({
cwd,
projectName,
template,
srcDir,
}: Omit<CustomTemplateOptions, 'mode'>) => {
shouldBeTemplateProject({ cwd, projectName, template, mode: 'js' })
shouldBeTemplateProject({ cwd, projectName, template, mode: 'js', srcDir })
}
export const shouldBeTypescriptProject = ({
cwd,
projectName,
template,
srcDir,
}: Omit<CustomTemplateOptions, 'mode'>) => {
shouldBeTemplateProject({ cwd, projectName, template, mode: 'ts' })
shouldBeTemplateProject({ cwd, projectName, template, mode: 'ts', srcDir })
}
......@@ -18,7 +18,7 @@ import {
import { useTempDir } from '../../../test/lib/use-temp-dir'
describe('create-next-app templates', () => {
if (!process.env.NEXT_TEST_CNA) {
if (!process.env.NEXT_TEST_CNA && process.env.NEXT_TEST_JOB) {
it('should skip when env is not set', () => {})
return
}
......@@ -30,7 +30,10 @@ describe('create-next-app templates', () => {
/**
* Start the create-next-app call.
*/
const childProcess = createNextApp([projectName, '--eslint'], { cwd })
const childProcess = createNextApp(
[projectName, '--eslint', '--no-src-dir', '--no-experimental-app'],
{ cwd }
)
/**
* Wait for the prompt to display.
*/
......@@ -62,9 +65,18 @@ describe('create-next-app templates', () => {
it('should create TS projects with --ts, --typescript', async () => {
await useTempDir(async (cwd) => {
const projectName = 'typescript-test'
const childProcess = createNextApp([projectName, '--ts', '--eslint'], {
cwd,
})
const childProcess = createNextApp(
[
projectName,
'--ts',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
......@@ -72,6 +84,27 @@ describe('create-next-app templates', () => {
})
})
it('should create TS projects with --ts, --typescript --src-dir', async () => {
await useTempDir(async (cwd) => {
const projectName = 'typescript-test'
const childProcess = createNextApp(
[projectName, '--ts', '--eslint', '--src-dir', '--no-experimental-app'],
{
cwd,
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeTypescriptProject({
cwd,
projectName,
template: 'default',
srcDir: true,
})
})
})
it('should create TS projects with --ts, --typescript with CI=1', async () => {
await useTempDir(async (cwd) => {
const projectName = 'typescript-test'
......@@ -93,19 +126,49 @@ describe('create-next-app templates', () => {
it('should create JS projects with --js, --javascript', async () => {
await useTempDir(async (cwd) => {
const projectName = 'javascript-test'
const childProcess = createNextApp([projectName, '--js', '--eslint'], {
cwd,
})
const childProcess = createNextApp(
[
projectName,
'--js',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeJavascriptProject({ cwd, projectName, template: 'default' })
})
})
it('should create JS projects with --js, --javascript --src-dir', async () => {
await useTempDir(async (cwd) => {
const projectName = 'javascript-test'
const childProcess = createNextApp(
[projectName, '--js', '--eslint', '--src-dir', '--no-experimental-app'],
{
cwd,
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeJavascriptProject({
cwd,
projectName,
template: 'default',
srcDir: true,
})
})
})
})
describe('create-next-app --experimental-app-dir', () => {
if (!process.env.NEXT_TEST_CNA) {
if (!process.env.NEXT_TEST_CNA && process.env.NEXT_TEST_JOB) {
it('should skip when env is not set', () => {})
return
}
......@@ -114,7 +177,14 @@ describe('create-next-app --experimental-app-dir', () => {
await useTempDir(async (cwd) => {
const projectName = 'appdir-test'
const childProcess = createNextApp(
[projectName, '--ts', '--experimental-app', '--eslint'],
[
projectName,
'--ts',
'--experimental-app',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
}
......@@ -130,7 +200,14 @@ describe('create-next-app --experimental-app-dir', () => {
await useTempDir(async (cwd) => {
const projectName = 'appdir-test'
const childProcess = createNextApp(
[projectName, '--js', '--experimental-app', '--eslint'],
[
projectName,
'--js',
'--experimental-app',
'--eslint',
'--no-src-dir',
'--no-experimental-app',
],
{
cwd,
}
......@@ -141,4 +218,27 @@ describe('create-next-app --experimental-app-dir', () => {
shouldBeTemplateProject({ cwd, projectName, template: 'app', mode: 'js' })
})
})
it('should create JS appDir projects with --js --src-dir', async () => {
await useTempDir(async (cwd) => {
const projectName = 'appdir-test'
const childProcess = createNextApp(
[projectName, '--js', '--experimental-app', '--eslint', '--src-dir'],
{
cwd,
stdio: 'inherit',
}
)
const exitCode = await spawnExitPromise(childProcess)
expect(exitCode).toBe(0)
shouldBeTemplateProject({
cwd,
projectName,
template: 'app',
mode: 'js',
srcDir: true,
})
})
})
})
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