一键导入格式化配置文件

89 阅读2分钟
#!/usr/bin/env node
const path = require('path')
const fs = require('fs')
const inquirer = require('inquirer')
const program = require('commander')
const { exec } = require('child_process')


console.log(process.argv);
program
  .command('init <type>')
  .option('-e,--eslint', 'add eslint config file')
  .option('-p,--prettier', 'add prettier config file')
  .option('-g,--gitignore', 'add gitignore config file')
  .action(async (type, cmd) => {
    //若用户选用了eslint选项,判断.eslintrc.js是否存在
    if (cmd.eslint) {
      //本包的bin.js文件同级下的配置文件路径,__dirname为该bin.js文件目录即脚本
      const originPath = path.join(__dirname, './.eslintrc.js')
      //项目安装该包,并使用命令,将要创建的配置文件的目的地址:当前命令行所在目录
      const dirPath = path.join('.eslintrc.js')
      const infoStr = 'eslint'
      await writeConfigHandel(dirPath, originPath, infoStr)
    }
    //若用户选用了gitignore选项,判断.gitignore是否存在
    if (cmd.gitignore) {
      //本包的bin.js文件同级下的配置文件路径,__dirname为该bin.js文件目录即脚本
      const originPath = path.join(__dirname, './_gitignore')
      //项目安装该包,并使用命令,将要创建的配置文件的目的地址:当前命令行所在目录
      const dirPath = path.join('.gitignore')
      const infoStr = 'gitignore'
      await writeConfigHandel(dirPath, originPath, infoStr)
    }
    //若用户选用了prettier选项,判断.prettierrc.js是否存在
    if (cmd.prettier) {
      inquirer
        .prompt([
          {
            type: 'confirm',
            name: 'confirmTag',
            message: '此操作将更改项目中vscode的setting配置,是否同意?',
            default: true,
          },
        ])
        .then(async (answers) => {
          //本包的bin.js文件同级下的配置文件路径,__dirname为该bin.js文件目录即脚本
          let originPath = path.join(__dirname, './_prettierrc')
          //项目安装该包,并使用命令,将要创建的配置文件的目的地址:当前命令行所在目录
          let dirPath = path.join('.prettierrc')
          let infoStr = 'prettier'
          await writeConfigHandel(dirPath, originPath, infoStr)

          //更改setting文件
          //本包的bin.js文件同级下的配置文件路径,__dirname为该bin.js文件目录即脚本
          originPath = path.join(__dirname, './settings.json')
          //项目安装该包,并使用命令,将要创建的配置文件的目的地址:当前命令行所在目录
          dirPath = path.join('./.vscode/settings.json')
          infoStr = 'settings'
          await writeConfigHandel(dirPath, originPath, infoStr)
        })
    }
  })
const writeConfigHandel = (dirPath, originPath, infoStr) => {
  return new Promise((resolve, reject) => {
    const writeHandel = () => {
      const data = fs.readFileSync(originPath)
      //二进制buffer序列,tostring转换成字符
      fs.writeFile(dirPath, data.toString(), (err) => {
        if (err) {
          console.log('\x1B[31m', '写入失败:', err, '\x1B[0m')
          reject(err)
          return false
        }
        console.log('\x1B[32m', `${infoStr}配置成功`, '\x1B[0m')
        resolve()
      })
    }

    //判断dirPath文件是否存在,存在提示覆盖,否则直接生成配置文件
    if (fs.existsSync(dirPath)) {
      inquirer
        .prompt([
          {
            type: 'confirm',
            name: 'replaceTag',
            message: `目录中已存在${infoStr}配置文件,是否覆盖?`,
            default: true,
          },
        ])
        .then((answers) => {
          if (answers.replaceTag) {
            //用户同意覆盖,将eslint配置写入
            writeHandel()
          }
        })
    } else {
      //获取文件目录
      let dirName = path.dirname(dirPath)
      //判断目录是否存在
      if (fs.existsSync(dirName)) {
        writeHandel()
      } else {
        //不存在目录,则递归创建目录
        fs.mkdir(dirName, { recursive: true }, (err) => {
          if (err) {
            console.log(
              '\x1B[31m',
              `创建目录${path.dirname(dirPath)}失败:`,
              err,
              '\x1B[0m'
            )
            reject(err)
          }
          writeHandel()
        })
      }
    }
  })
}
program.parse(process.argv)

webpack配置

{
  "name": "my-npm",
  "version": "0.0.1",
  "description": "我的包管理工具",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "files":[
    "bin"
  ],
  "bin": {
    "xyc-cli": "bin/bin.js"
  },
  "author": "xyc",
  "license": "ISC",
  "dependencies": {
    "commander": "^8.3.0",
    "inquirer": "^8.2.0"
  }
}

目录结构:

image.png

npm命令: npm pack打包成tgz的安装包文件-----在项目中npm i 生成包的目录位置就可以安装该工具

npm publish上传到npm库-----项目中npm i name就行