2021-07-26 14:46:19 +00:00
|
|
|
import { promises as fsp } from 'fs'
|
|
|
|
import { relative, resolve } from 'upath'
|
|
|
|
import { cyan } from 'colorette'
|
2021-08-09 20:54:12 +00:00
|
|
|
import type { TSReference } from '@nuxt/kit'
|
2021-07-26 14:46:19 +00:00
|
|
|
import { requireModule, getModulePaths, getNearestPackage } from '../utils/cjs'
|
|
|
|
import { success } from '../utils/log'
|
|
|
|
import { defineNuxtCommand } from './index'
|
|
|
|
|
|
|
|
export default defineNuxtCommand({
|
|
|
|
meta: {
|
|
|
|
name: 'prepare',
|
|
|
|
usage: 'nu prepare',
|
|
|
|
description: 'Prepare nuxt for development/build'
|
|
|
|
},
|
|
|
|
async invoke (args) {
|
|
|
|
process.env.NODE_ENV = process.env.NODE_ENV || 'production'
|
|
|
|
const rootDir = resolve(args._[0] || '.')
|
|
|
|
|
|
|
|
const { loadNuxt } = requireModule('@nuxt/kit', rootDir) as typeof import('@nuxt/kit')
|
|
|
|
const nuxt = await loadNuxt({ rootDir })
|
|
|
|
|
|
|
|
const adHocModules = nuxt.options._majorVersion === 3
|
|
|
|
? ['@nuxt/kit', '@nuxt/app', '@nuxt/nitro']
|
|
|
|
: ['@nuxt/kit']
|
|
|
|
|
2021-08-09 20:54:12 +00:00
|
|
|
const modulePaths = getModulePaths(nuxt.options.modulesDir)
|
|
|
|
|
|
|
|
const references: TSReference[] = [
|
2021-07-26 14:46:19 +00:00
|
|
|
...adHocModules,
|
|
|
|
...nuxt.options.buildModules,
|
|
|
|
...nuxt.options.modules,
|
|
|
|
...nuxt.options._modules
|
2021-08-09 20:54:12 +00:00
|
|
|
]
|
|
|
|
.filter(f => typeof f === 'string')
|
|
|
|
.map(id => ({ types: getNearestPackage(id, modulePaths)?.name || id }))
|
2021-07-26 14:46:19 +00:00
|
|
|
|
2021-08-09 20:54:12 +00:00
|
|
|
const declarations: string[] = []
|
2021-07-26 14:46:19 +00:00
|
|
|
|
2021-08-09 20:54:12 +00:00
|
|
|
await nuxt.callHook('builder:generateApp')
|
|
|
|
await nuxt.callHook('prepare:types', { references, declarations })
|
2021-07-26 14:46:19 +00:00
|
|
|
|
|
|
|
const declarationPath = resolve(`${rootDir}/nuxt.d.ts`)
|
|
|
|
|
|
|
|
const declaration = [
|
2021-08-09 20:54:12 +00:00
|
|
|
'// This file is auto generated by `nuxt prepare`',
|
|
|
|
'// Please do not manually modify this file.',
|
2021-07-26 14:46:19 +00:00
|
|
|
'',
|
2021-08-09 21:54:44 +00:00
|
|
|
...references.map((ref) => {
|
|
|
|
if ('path' in ref) {
|
|
|
|
ref.path = relative(rootDir, ref.path)
|
|
|
|
}
|
|
|
|
return `/// <reference ${renderAttrs(ref)} />`
|
|
|
|
}),
|
2021-08-09 20:54:12 +00:00
|
|
|
...declarations,
|
|
|
|
'export {}',
|
2021-07-26 14:46:19 +00:00
|
|
|
''
|
|
|
|
].join('\n')
|
|
|
|
|
|
|
|
await fsp.writeFile(declarationPath, declaration)
|
|
|
|
|
|
|
|
success('Generated', cyan(relative(process.cwd(), declarationPath)))
|
|
|
|
}
|
|
|
|
})
|
2021-08-09 20:54:12 +00:00
|
|
|
|
|
|
|
function renderAttrs (obj) {
|
|
|
|
return Object.entries(obj).map(e => renderAttr(e[0], e[1])).join(' ')
|
|
|
|
}
|
|
|
|
|
|
|
|
function renderAttr (key, value) {
|
|
|
|
return value ? `${key}="${value}"` : ''
|
|
|
|
}
|