Unverified Commit bca6ff77 authored by Balázs Orbán's avatar Balázs Orbán Committed by GitHub

fix(cna): separate `dependencies`/`devDependencies` (#55730)

### What?

As [discussed](https://vercel.slack.com/archives/C04DUD7EB1B/p1692183798097169), we should follow the ecosystem standard separation of dependencies and dev dependencies.

### Why?

This is a common issue/misunderstanding that we always have to explain separately, while there is no real benefit.

One counter-argument was that install times would be increased when we had to run install for `dependencies` and `devDependencies` separately, but that's easy to work around as explained below.

### How?

Instead of passing the `dependencies` array to the package manager in the CLI, we write these to the `package.json` file and then run the package manager's install command without the dependency arguments.

This will also reduce the number of writes to the `package.json` file from two to just one.

Ref: https://github.com/vercel/next.js/pull/42218, https://github.com/vercel/next.js/pull/48076, https://github.com/vercel/next.js/issues/54105, https://github.com/vercel/next.js/pull/42012, and more

[Slack thread](https://vercel.slack.com/archives/C04DUD7EB1B/p1692183798097169)
Co-authored-by: 's avatarSteven <229881+styfle@users.noreply.github.com>
parent fabab8cf
......@@ -215,7 +215,7 @@ export async function createApp({
console.log('Installing packages. This might take a couple of minutes.')
console.log()
await install(root, null, { packageManager, isOnline })
await install(packageManager, isOnline)
console.log()
}
} else {
......
......@@ -3,103 +3,32 @@ import { yellow } from 'picocolors'
import spawn from 'cross-spawn'
import type { PackageManager } from './get-pkg-manager'
interface InstallArgs {
/**
* Indicate whether to install packages using npm, pnpm or Yarn.
*/
packageManager: PackageManager
/**
* Indicate whether there is an active Internet connection.
*/
isOnline: boolean
/**
* Indicate whether the given dependencies are devDependencies.
*/
devDependencies?: boolean
}
/**
* Spawn a package manager installation with either Yarn or NPM.
* Spawn a package manager installation based on user preference.
*
* @returns A Promise that resolves once the installation is finished.
*/
export function install(
root: string,
dependencies: string[] | null,
{ packageManager, isOnline, devDependencies }: InstallArgs
export async function install(
/** Indicate which package manager to use. */
packageManager: PackageManager,
/** Indicate whether there is an active Internet connection.*/
isOnline: boolean
): Promise<void> {
/**
* (p)npm-specific command-line flags.
*/
const npmFlags: string[] = []
/**
* Yarn-specific command-line flags.
*/
const yarnFlags: string[] = []
let args: string[] = ['install']
if (!isOnline) {
console.log(
yellow('You appear to be offline.\nFalling back to the local cache.')
)
args.push('--offline')
}
/**
* Return a Promise that resolves once the installation is finished.
*/
return new Promise((resolve, reject) => {
let args: string[]
let command = packageManager
const useYarn = packageManager === 'yarn'
const useBun = packageManager === 'bun'
if (dependencies && dependencies.length) {
/**
* If there are dependencies, run a variation of `{packageManager} add`.
*/
if (useYarn) {
/**
* Call `yarn add --exact (--offline)? (-D)? ...`.
*/
args = ['add', '--exact']
if (!isOnline) args.push('--offline')
args.push('--cwd', root)
if (devDependencies) args.push('--dev')
args.push(...dependencies)
} else if (useBun) {
args = ['add', '--exact']
args.push('--cwd', root)
if (devDependencies) args.push('--development')
args.push(...dependencies)
} else {
/**
* Call `(p)npm install [--save|--save-dev] ...`.
*/
args = ['install', '--save-exact']
args.push(devDependencies ? '--save-dev' : '--save')
args.push(...dependencies)
}
} else {
/**
* If there are no dependencies, run a variation of `{packageManager}
* install`.
*/
args = ['install']
if (!isOnline) {
console.log(yellow('You appear to be offline.'))
if (useYarn) {
console.log(yellow('Falling back to the local Yarn cache.'))
console.log()
args.push('--offline')
} else {
console.log()
}
}
}
/**
* Add any package manager-specific flags.
*/
if (useYarn) {
args.push(...yarnFlags)
} else {
args.push(...npmFlags)
}
/**
* Spawn the installation process.
*/
const child = spawn(command, args, {
const child = spawn(packageManager, args, {
stdio: 'inherit',
env: {
...process.env,
......@@ -112,7 +41,7 @@ export function install(
})
child.on('close', (code) => {
if (code !== 0) {
reject({ command: `${command} ${args.join(' ')}` })
reject({ command: `${packageManager} ${args.join(' ')}` })
return
}
resolve()
......
......@@ -4,7 +4,7 @@ import { copy } from '../helpers/copy'
import { async as glob } from 'fast-glob'
import os from 'os'
import fs from 'fs'
import fs from 'fs/promises'
import path from 'path'
import { cyan, bold } from 'picocolors'
import { Sema } from 'async-sema'
......@@ -79,9 +79,9 @@ export const installTemplate = async ({
root,
mode === 'js' ? 'jsconfig.json' : 'tsconfig.json'
)
await fs.promises.writeFile(
await fs.writeFile(
tsconfigFile,
(await fs.promises.readFile(tsconfigFile, 'utf8'))
(await fs.readFile(tsconfigFile, 'utf8'))
.replace(
`"@/*": ["./*"]`,
srcDir ? `"@/*": ["./src/*"]` : `"@/*": ["./*"]`
......@@ -103,11 +103,11 @@ export const installTemplate = async ({
if (file === 'tsconfig.json' || file === 'jsconfig.json') return
await writeSema.acquire()
const filePath = path.join(root, file)
if ((await fs.promises.stat(filePath)).isFile()) {
await fs.promises.writeFile(
if ((await fs.stat(filePath)).isFile()) {
await fs.writeFile(
filePath,
(
await fs.promises.readFile(filePath, 'utf8')
await fs.readFile(filePath, 'utf8')
).replace(`@/`, `${importAlias.replace(/\*/g, '')}`)
)
}
......@@ -120,7 +120,7 @@ export const installTemplate = async ({
await makeDir(path.join(root, 'src'))
await Promise.all(
SRC_DIR_NAMES.map(async (file) => {
await fs.promises
await fs
.rename(path.join(root, file), path.join(root, 'src', file))
.catch((err) => {
if (err.code !== 'ENOENT') {
......@@ -139,10 +139,10 @@ export const installTemplate = async ({
`${isAppTemplate ? 'page' : 'index'}.${mode === 'ts' ? 'tsx' : 'js'}`
)
await fs.promises.writeFile(
await fs.writeFile(
indexPageFile,
(
await fs.promises.readFile(indexPageFile, 'utf8')
await fs.readFile(indexPageFile, 'utf8')
).replace(
isAppTemplate ? 'app/page' : 'pages/index',
isAppTemplate ? 'src/app/page' : 'src/pages/index'
......@@ -154,10 +154,10 @@ export const installTemplate = async ({
root,
mode === 'ts' ? 'tailwind.config.ts' : 'tailwind.config.js'
)
await fs.promises.writeFile(
await fs.writeFile(
tailwindConfigFile,
(
await fs.promises.readFile(tailwindConfigFile, 'utf8')
await fs.readFile(tailwindConfigFile, 'utf8')
).replace(
/\.\/(\w+)\/\*\*\/\*\.\{js,ts,jsx,tsx,mdx\}/g,
'./src/$1/**/*.{js,ts,jsx,tsx,mdx}'
......@@ -166,10 +166,8 @@ export const installTemplate = async ({
}
}
/**
* Create a package.json for the new project and write it to disk.
*/
const packageJson = {
/** Create a package.json for the new project and write it to disk. */
const packageJson: any = {
name: appName,
version: '0.1.0',
private: true,
......@@ -179,69 +177,70 @@ export const installTemplate = async ({
start: 'next start',
lint: 'next lint',
},
/**
* Default dependencies.
*/
dependencies: {
react: 'latest',
'react-dom': 'latest',
next: process.env.NEXT_PRIVATE_TEST_VERSION ?? 'latest',
},
devDependencies: {},
}
await fs.promises.writeFile(
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${
process.env.NEXT_PRIVATE_TEST_VERSION
? `@${process.env.NEXT_PRIVATE_TEST_VERSION}`
: ''
}`,
]
/**
* TypeScript projects will have type definitions and other devDependencies.
*/
if (mode === 'ts') {
dependencies.push(
'typescript',
'@types/react',
'@types/node',
'@types/react-dom'
)
packageJson.devDependencies = {
...packageJson.devDependencies,
typescript: 'latest',
'@types/react': 'latest',
'@types/node': 'latest',
'@types/react-dom': 'latest',
}
}
/**
* Add Tailwind CSS dependencies.
*/
/* Add Tailwind CSS dependencies. */
if (tailwind) {
dependencies.push('tailwindcss', 'postcss', 'autoprefixer')
packageJson.devDependencies = {
...packageJson.devDependencies,
autoprefixer: 'latest',
postcss: 'latest',
tailwindcss: 'latest',
}
}
/**
* Default eslint dependencies.
*/
/* Default ESLint dependencies. */
if (eslint) {
dependencies.push('eslint', 'eslint-config-next')
}
/**
* Install package.json dependencies if they exist.
*/
if (dependencies.length) {
console.log()
console.log('Installing dependencies:')
for (const dependency of dependencies) {
console.log(`- ${cyan(dependency)}`)
packageJson.devDependencies = {
...packageJson.devDependencies,
eslint: 'latest',
'eslint-config-next': 'latest',
}
console.log()
}
const devDeps = Object.keys(packageJson.devDependencies).length
if (!devDeps) delete packageJson.devDependencies
await install(root, dependencies, installFlags)
await fs.writeFile(
path.join(root, 'package.json'),
JSON.stringify(packageJson, null, 2) + os.EOL
)
console.log('\nInstalling dependencies:')
for (const dependency in packageJson.dependencies)
console.log(`- ${cyan(dependency)}`)
if (devDeps) {
console.log('\nInstalling devDependencies:')
for (const dependency in packageJson.devDependencies)
console.log(`- ${cyan(dependency)}`)
}
console.log()
await install(packageManager, isOnline)
}
export * from './types'
......@@ -30,8 +30,8 @@ export const projectSpecification: ProjectSpecification = {
'node_modules/next',
'.gitignore',
],
deps: ['next', 'react', 'react-dom', 'eslint', 'eslint-config-next'],
devDeps: [],
deps: ['next', 'react', 'react-dom'],
devDeps: ['eslint', 'eslint-config-next'],
},
default: {
js: {
......@@ -52,8 +52,13 @@ export const projectSpecification: ProjectSpecification = {
'tsconfig.json',
'next-env.d.ts',
],
deps: ['@types/node', '@types/react', '@types/react-dom', 'typescript'],
devDeps: [],
deps: [],
devDeps: [
'@types/node',
'@types/react',
'@types/react-dom',
'typescript',
],
},
},
'default-tw': {
......@@ -66,8 +71,8 @@ export const projectSpecification: ProjectSpecification = {
'postcss.config.js',
'tailwind.config.js',
],
deps: ['autoprefixer', 'postcss', 'tailwindcss'],
devDeps: [],
deps: [],
devDeps: ['autoprefixer', 'postcss', 'tailwindcss'],
},
ts: {
files: [
......@@ -79,7 +84,8 @@ export const projectSpecification: ProjectSpecification = {
'tailwind.config.ts',
'tsconfig.json',
],
deps: [
deps: [],
devDeps: [
'@types/node',
'@types/react-dom',
'@types/react',
......@@ -88,7 +94,6 @@ export const projectSpecification: ProjectSpecification = {
'tailwindcss',
'typescript',
],
devDeps: [],
},
},
app: {
......@@ -98,8 +103,13 @@ export const projectSpecification: ProjectSpecification = {
files: ['app/page.js', 'app/layout.js', 'jsconfig.json'],
},
ts: {
deps: ['@types/node', '@types/react', '@types/react-dom', 'typescript'],
devDeps: [],
deps: [],
devDeps: [
'@types/node',
'@types/react',
'@types/react-dom',
'typescript',
],
files: [
'app/page.tsx',
'app/layout.tsx',
......@@ -110,8 +120,8 @@ export const projectSpecification: ProjectSpecification = {
},
'app-tw': {
js: {
deps: ['autoprefixer', 'postcss', 'tailwindcss'],
devDeps: [],
deps: [],
devDeps: ['autoprefixer', 'postcss', 'tailwindcss'],
files: [
'app/layout.js',
'app/page.js',
......@@ -121,7 +131,8 @@ export const projectSpecification: ProjectSpecification = {
],
},
ts: {
deps: [
deps: [],
devDeps: [
'@types/node',
'@types/react-dom',
'@types/react',
......@@ -130,7 +141,6 @@ export const projectSpecification: ProjectSpecification = {
'tailwindcss',
'typescript',
],
devDeps: [],
files: [
'app/layout.tsx',
'app/page.tsx',
......
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