template-ivan
Version:
57 lines (44 loc) • 1.78 kB
JavaScript
/* eslint-disable import/no-unresolved, max-params, global-require */
const fs = require('fs-extra')
const path = require('path')
const chalk = require('chalk')
const spawn = require('cross-spawn')
/**
* react项目初始化
* @param {string} appPath 被构建的项目目录
* @param {string} appName 被构建的项目名
* @param {string} template 被构建的模版名
*/
function command(appPath, appName, template = 'react') {
const ownPackageName = require(path.join(__dirname, 'package.json')).name
const ownPath = path.join(appPath, 'node_modules', ownPackageName)
// delete package.json
fs.removeSync(path.join(appPath, 'package.json'))
// Copy the files for the user
const templatePath = path.join(ownPath, template)
fs.copySync(templatePath, appPath)
const appPackage = require(path.join(appPath, 'package.json'))
// Setup the app name
appPackage.name = appName
// 对象补充赋值属性,然后进行赋值
fs.writeFileSync(
path.join(appPath, 'package.json'),
JSON.stringify(appPackage, null, 2),
)
// Rename gitignore after the fact to prevent npm from renaming it to .npmignore
// See: https://github.com/npm/npm/issues/1862
fs.move(
path.join(appPath, 'gitignore'),
path.join(appPath, '.gitignore'),
).then(console.error)
fs.removeSync(path.join(appPath, 'node_modules', ownPackageName))
// Install react, react-dom, react-router and so on
const proc = spawn.sync('npm', ['install'], { stdio: 'inherit' })
if (proc.status !== 0) {
console.error(chalk.red('\nInstall package failed'))
return
}
console.log(chalk.green(`Success! Created ${chalk.yellow(appName)} at ${chalk.yellow(appPath)}`))
}
module.exports = command