Nuxt/packages/nuxi/src/commands/init.ts

70 lines
2.3 KiB
TypeScript
Raw Normal View History

import { existsSync, readdirSync } from 'node:fs'
// @ts-expect-error missing types
import createTiged from 'tiged'
2021-10-05 20:35:23 +00:00
import { relative, resolve } from 'pathe'
import superb from 'superb'
import consola from 'consola'
2021-10-05 20:35:23 +00:00
import { defineNuxtCommand } from './index'
const rpath = (p: string) => relative(process.cwd(), p)
2021-10-05 20:35:23 +00:00
const resolveTemplate = (template: string | boolean) => {
if (typeof template === 'boolean') {
consola.error('Please specify a template!')
process.exit(1)
}
if (!template) {
template = 'v3'
}
if (template.includes('/')) {
return template
}
return `nuxt/starter#${template}`
}
2021-10-05 20:35:23 +00:00
export default defineNuxtCommand({
meta: {
name: 'init',
2021-11-02 09:50:04 +00:00
usage: 'npx nuxi init|create [--verbose|-v] [--template,-t] [dir]',
2021-10-05 20:35:23 +00:00
description: 'Initialize a fresh project'
},
async invoke (args) {
// Clone template
const src = resolveTemplate(args.template || args.t)
2021-10-05 20:35:23 +00:00
const dstDir = resolve(process.cwd(), args._[0] || 'nuxt-app')
const tiged = createTiged(src, { cache: false /* TODO: buggy */, verbose: (args.verbose || args.v) })
2021-10-05 20:35:23 +00:00
if (existsSync(dstDir) && readdirSync(dstDir).length) {
consola.error(`Directory ${dstDir} is not empty. Please pick another name or remove it first. Aborting.`)
2021-10-05 20:35:23 +00:00
process.exit(1)
}
const formatArgs = (msg: string) => msg.replace('options.', '--')
tiged.on('warn', (event: any) => consola.warn(formatArgs(event.message)))
tiged.on('info', (event: any) => consola.info(formatArgs(event.message)))
try {
await tiged.clone(dstDir)
} catch (e: any) {
if (e.toString().includes('could not find commit hash')) {
consola.error(`Failed to clone template from \`${src}\`. Please check the repo is valid and that you have installed \`git\` correctly.`)
process.exit(1)
}
throw e
}
2021-10-05 20:35:23 +00:00
// Show next steps
const relativeDist = rpath(dstDir)
const nextSteps = [
relativeDist.length > 1 && `📁 \`cd ${relativeDist}\``,
'💿 Install dependencies with `npm install` or `yarn install` or `pnpm install --shamefully-hoist`',
'🚀 Start development server with `npm run dev` or `yarn dev` or `pnpm run dev`'
].filter(Boolean)
consola.log(`\n ✨ Your ${superb.random()} Nuxt project is just created! Next steps:\n`)
for (const step of nextSteps) {
consola.log(` ${step}\n`)
}
2021-10-05 20:35:23 +00:00
}
})