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