欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3組件庫添加腳本的實現(xiàn)示例

 更新時間:2024年06月28日 09:24:57   作者:程序員長夜  
本文主要介紹了vue3組件庫添加腳本的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

添加腳本

在操作組件庫的時候有一些操作比較繁瑣,因此添加腳本,通過腳本執(zhí)行這些繁瑣的事情

在項目根目錄創(chuàng)建script?目錄

添加組件

創(chuàng)建組件目錄及固定結(jié)構(gòu)

每次新建組件都需要徐建如下操作:

  • 在packages文件夾中創(chuàng)建組件目錄
  • 在docs\demos中創(chuàng)建組件的目錄
  • 在docs\components中創(chuàng)建組件目錄
  • ……

通過編寫一些腳本幫我自動創(chuàng)建對應(yīng)的文件夾和文件,在script?目錄創(chuàng)建add.js?和tools.js?文件以及創(chuàng)建add?文件夾,在add?文件夾下創(chuàng)建directoryFile.js?文件

:::demo
${componentName}/index
:::

`;

  //   文檔目錄
  const directory = path.join(docPath, componentName);

  // 判斷是否有工具路徑
  const isExists = fs.existsSync(directory);
  if (isExists) {
    exit(`${directory}目錄已經(jīng)存在`);
  }

  // 文檔路徑
  const documentPath = path.join(directory, "/base.md");
  fs.mkdirSync(directory);
  // 寫入文件
  fs.writeFileSync(documentPath, documentTemplate); // 工具
  myLog("創(chuàng)建組件文檔", documentPath);

  //  -------  創(chuàng)建組件文檔 end ------

  // ---------創(chuàng)建組件demo start -----

  // demo路徑
  const demoPath = path.join(__dirname, "../../docs/demos");
  //   demo目錄
  const demoDirectory = path.join(demoPath, componentName);
  // 創(chuàng)建文件夾
  fs.mkdirSync(demoDirectory);
  // 文件路徑
  const demoFilePath = path.join(demoDirectory, "/index.vue");
  // demo 模板
  const demoTemplate = `<template>
  <div>
    <${capitalizeFirstLetter(componentName)} />
  </div>
</template>

<script>
export default {
  name: "${componentName}-demo",
};
</script>

<style lang="scss" scoped>

</style>`;

  // 寫入文件
  fs.writeFileSync(demoFilePath, demoTemplate); // 工具
  myLog("創(chuàng)建demo文件", demoFilePath);

  // ---------創(chuàng)建組件demo end -----

  // ---------創(chuàng)建組件 start -----

  // 組件路徑
  const componentPath = path.join(__dirname, "../../packages");
  // 組件目錄
  const componentDirectory = path.join(componentPath, componentName);
  // 創(chuàng)建文件夾
  fs.mkdirSync(componentDirectory);

  // 組件主目錄
  const componentMainDirectory = path.join(componentDirectory, "src");
  // 創(chuàng)建文件夾
  fs.mkdirSync(componentMainDirectory);
  // 組件主文件
  const componentMainFilePath = path.join(componentMainDirectory, "/index.vue");
  // 組件內(nèi)容
  const componentTemplate = `<template>
  <div>
    <div>${componentName}</div>
  </div>
</template>

<script>
export default {
  name: "${componentName}",
};
</script>

<style lang="scss" scoped>

</style>`;
  fs.writeFileSync(componentMainFilePath, componentTemplate);
  // 組件安裝文件
  const componentInstallPath = path.join(componentDirectory, "index.ts");
  // 判斷導(dǎo)入組件組件組件使用大寫還是小寫
  let subassembly =
    capitalizeFirstLetter(componentName) === componentName
      ? lowerFirstLetter(componentName)
      : capitalizeFirstLetter(componentName);

  // 組件安裝
  const componentInstall = `import ${subassembly} from "./src/index.vue";
import { withInstall } from "../withInstall";

const ${capitalizeFirstLetter(componentName)} = withInstall(${subassembly});
export default ${capitalizeFirstLetter(componentName)};`;

  // 寫入文件
  fs.writeFileSync(componentInstallPath, componentInstall);

  myLog("創(chuàng)建組件目錄", componentDirectory);
  // ---------創(chuàng)建組件 end -----
};

組件介紹

:::demo
${componentName}/index
:::

`;

  //   文檔目錄
  const directory = path.join(docPath, componentName);

  // 判斷是否有工具路徑
  const isExists = fs.existsSync(directory);
  if (isExists) {
    exit(`${directory}目錄已經(jīng)存在`);
  }

  // 文檔路徑
  const documentPath = path.join(directory, "/base.md");
  fs.mkdirSync(directory);
  // 寫入文件
  fs.writeFileSync(documentPath, documentTemplate); // 工具
  myLog("創(chuàng)建組件文檔", documentPath);

  //  -------  創(chuàng)建組件文檔 end ------

  // ---------創(chuàng)建組件demo start -----

  // demo路徑
  const demoPath = path.join(__dirname, "../../docs/demos");
  //   demo目錄
  const demoDirectory = path.join(demoPath, componentName);
  // 創(chuàng)建文件夾
  fs.mkdirSync(demoDirectory);
  // 文件路徑
  const demoFilePath = path.join(demoDirectory, "/index.vue");
  // demo 模板
  const demoTemplate = `<template>
  <div>
    <${capitalizeFirstLetter(componentName)} />
  </div>
</template>

<script>
export default {
  name: "${componentName}-demo",
};
</script>

<style lang="scss" scoped>

</style>`;

  // 寫入文件
  fs.writeFileSync(demoFilePath, demoTemplate); // 工具
  myLog("創(chuàng)建demo文件", demoFilePath);

  // ---------創(chuàng)建組件demo end -----

  // ---------創(chuàng)建組件 start -----

  // 組件路徑
  const componentPath = path.join(__dirname, "../../packages");
  // 組件目錄
  const componentDirectory = path.join(componentPath, componentName);
  // 創(chuàng)建文件夾
  fs.mkdirSync(componentDirectory);

  // 組件主目錄
  const componentMainDirectory = path.join(componentDirectory, "src");
  // 創(chuàng)建文件夾
  fs.mkdirSync(componentMainDirectory);
  // 組件主文件
  const componentMainFilePath = path.join(componentMainDirectory, "/index.vue");
  // 組件內(nèi)容
  const componentTemplate = `<template>
  <div>
    <div>${componentName}</div>
  </div>
</template>

<script>
export default {
  name: "${componentName}",
};
</script>

<style lang="scss" scoped>

</style>`;
  fs.writeFileSync(componentMainFilePath, componentTemplate);
  // 組件安裝文件
  const componentInstallPath = path.join(componentDirectory, "index.ts");
  // 判斷導(dǎo)入組件組件組件使用大寫還是小寫
  let subassembly =
    capitalizeFirstLetter(componentName) === componentName
      ? lowerFirstLetter(componentName)
      : capitalizeFirstLetter(componentName);

  // 組件安裝
  const componentInstall = `import ${subassembly} from "./src/index.vue";
import { withInstall } from "../withInstall";

const ${capitalizeFirstLetter(componentName)} = withInstall(${subassembly});
export default ${capitalizeFirstLetter(componentName)};`;

  // 寫入文件
  fs.writeFileSync(componentInstallPath, componentInstall);

  myLog("創(chuàng)建組件目錄", componentDirectory);
  // ---------創(chuàng)建組件 end -----
};

在add.js?導(dǎo)入

/* eslint-disable no-undef */

import { warn } from "./tools.js";
import { directoryFile } from "./add/directoryFile.js";

// 組件名稱
let componentName = process.argv[2];
if (!componentName) {
  warn("Usage: npm run add <component-name>");
  process.exit(1);
}

// 創(chuàng)建目錄
 directoryFile();

然后在package.json?中添加命令就可以了

"add": "node ./script/add.js"

這樣需要創(chuàng)建組件的時候只需要在命令行中輸入

npm run add  組件名稱

修改components.d.ts

上面的操作創(chuàng)建了組件的目錄及基本結(jié)構(gòu),在創(chuàng)建組件的時候還需要再components.d.ts?引入組件設(shè)置類型
因此在add?文件夾下面創(chuàng)建add-componentDTs.js?文件,并在add.js?中引入

/* eslint-disable no-undef */
// 添加 packages\components.d.ts 文件中的類型

import fs from "fs-extra";
import { myLog, capitalizeFirstLetter } from "../tools.js";
const componentName = process.argv[2]; // 從命令行參數(shù)獲取組件名

// 需要處理的文件路徑
const filePath = "./packages/components.d.ts"; // 文件路徑,請?zhí)鎿Q為實際路徑
// 需要導(dǎo)入的組件路徑
const importPath = `./${componentName.toLowerCase()}/src/index.vue`; // 假設(shè)組件的導(dǎo)入路徑與組件名相關(guān)聯(lián)
// 導(dǎo)入組件
const importStatement = `import ${capitalizeFirstLetter(componentName)} from "${importPath}";\n`;
// 組件類型
const componentDeclaration = `\t${capitalizeFirstLetter(componentName)}: typeof ${capitalizeFirstLetter(componentName)};\n`;

async function addComponent() {
  try {
    let fileContent = await fs.readFile(filePath, "utf8");

    // 檢查是否已存在該組件的導(dǎo)入和聲明,避免重復(fù)添加
    if (!fileContent.includes(importStatement) && !fileContent.includes(componentDeclaration)) {
      // 在導(dǎo)入部分添加新組件導(dǎo)入
      // eslint-disable-next-line quotes
      const importSectionEndIndex = fileContent.indexOf('declare module "vue"');
      fileContent =
        fileContent.slice(0, importSectionEndIndex) +
        importStatement +
        fileContent.slice(importSectionEndIndex);

      // 在GlobalComponents接口中添加新組件聲明
      const globalComponentsStartIndex = fileContent.indexOf("{", importSectionEndIndex);
      const globalComponentsEndIndex = fileContent.indexOf("}", importSectionEndIndex);
      // 提取出 導(dǎo)出的類型
      const globalComponentsSection = fileContent.slice(
        globalComponentsStartIndex,
        globalComponentsEndIndex,
      );
      fileContent = fileContent.replace(
        globalComponentsSection,
        `${globalComponentsSection}${componentDeclaration}`,
      );

      await fs.writeFile(filePath, fileContent, "utf8");
      // console.log(`Component ${componentName} has been added successfully.`);
      myLog(`Component ${componentName} has been added successfully.`);
    } else {
      // console.log(`Component ${componentName} is already present in the file.`);
      myLog(`Component ${componentName} is already present in the file.`);
    }
  } catch (error) {
    console.error("An error occurred:", error);
  }
}

export default addComponent;

修改index.ts

在add?文件夾下面創(chuàng)建add-indexTs.js?文件

/* eslint-disable no-undef */
import fs from "fs";
import { myLog, capitalizeFirstLetter } from "../tools.js";

// 指定要修改的文件路徑
const filePath = "./packages/index.ts"; // 要添加的組件名稱
const componentName = process.argv[process.argv.length - 1]; // 從命令行參數(shù)獲取,如 'abc'

// 確保組件名符合導(dǎo)入語句的格式
const formattedComponentName = componentName.replace(/\.vue$/, "").replace(/^\//, "");
export const addIndexTs = () => {
  // 讀取文件內(nèi)容
  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) {
      console.error(`讀取文件失敗: ${err}`);
      return;
    }

    // 添加導(dǎo)入語句在現(xiàn)有導(dǎo)入語句之后(如果尚未存在)
    const importRegex = /import\s+.+?from\s+["'].*?["'];/g;
    let lastImportMatch;
    while ((lastImportMatch = importRegex.exec(data)) !== null) {
      // 找到最后一個匹配的導(dǎo)入語句
    }
    const importLine = `\nimport ${capitalizeFirstLetter(formattedComponentName)} from "./${formattedComponentName}";\n`;
    if (!lastImportMatch || !data.includes(importLine)) {
      const insertPosition = lastImportMatch
        ? lastImportMatch.index + lastImportMatch[0].length
        : data.indexOf("const components:");
      data = data.slice(0, insertPosition) + importLine + data.slice(insertPosition);
    }

    // 更新組件列表(如果尚未存在)
    const componentsStart = "const components: { [propName: string]: Component } = {";
    const componentsEnd = "};";
    const componentsIndexStart = data.indexOf(componentsStart);
    const componentsIndexEnd = data.indexOf(componentsEnd, componentsIndexStart);
    if (componentsIndexStart !== -1 && componentsIndexEnd !== -1) {
      let componentsBlock = data.substring(
        componentsIndexStart,
        componentsIndexEnd + componentsEnd.length,
      );
      if (!componentsBlock.includes(`${formattedComponentName}:`)) {
        componentsBlock = componentsBlock.replace(
          componentsEnd,
          `  ${capitalizeFirstLetter(formattedComponentName)},\n${componentsEnd}`,
        );
        data =
          data.substring(0, componentsIndexStart) +
          componentsBlock +
          data.substring(componentsIndexEnd + componentsEnd.length);
      }
    }

    // 更新導(dǎo)出語句
    const exportStart = "export {";
    const exportEnd = "};";
    const exportIndexStart = data.lastIndexOf(exportStart);
    const exportIndexEnd = data.indexOf(exportEnd, exportIndexStart);
    if (exportIndexStart !== -1 && exportIndexEnd !== -1) {
      let exportsBlock = data.substring(exportIndexStart, exportIndexEnd + exportEnd.length);
      if (!exportsBlock.includes(`${formattedComponentName},`)) {
        const currentExports = exportsBlock
          .replace(exportStart, "")
          .replace(exportEnd, "")
          .trim()
          .split(",")
          .map(s => s.trim());
        if (currentExports[currentExports.length - 1] !== "") {
          currentExports.push(capitalizeFirstLetter(formattedComponentName));
          exportsBlock = `${exportStart} ${currentExports.join(", ")} ${exportEnd}`;
        } else {
          exportsBlock = exportsBlock.replace(
            exportEnd,
            `, ${formattedComponentName}\n${exportEnd}`,
          );
        }
        data =
          data.substring(0, exportIndexStart) +
          exportsBlock +
          data.substring(exportIndexEnd + exportEnd.length);
      }
    }

    // 寫回文件
    fs.writeFile(filePath, data, "utf8", err => {
      if (err) {
        console.error(`寫入文件失敗: ${err}`);
      } else {
        myLog(`${formattedComponentName} 已成功添加到文件`, "packages/index.ts");
      }
    });
  });
};

添加vitePress菜單

經(jīng)過以上操作添加組件基本完成,還剩余添加說明文檔的側(cè)邊欄
在add?文件夾中創(chuàng)建add-vitePressConfig.js?

/* eslint-disable no-undef */
import fs from "fs";
import { myLog } from "../tools.js";

const vitePressConfig = "./docs/.vitepress/config.ts";

const componentName = process.argv[2]; // 從命令行參數(shù)獲取,如 'abc'
const componentNameCn = process.argv[3]; // 從命令行參數(shù)獲取,如 'abc'

const addMenu = `{ text: "${componentNameCn || "組件名稱"}", link: "/components/${componentName}/base.md" },`;

export const addVitePressConfig = () => {
  // 讀取文件
  fs.readFile(vitePressConfig, "utf8", (err, data) => {
    if (err) {
      console.error(`讀取文件失敗: ${err}`);
      return;
    }

    let componentsIndexStart = data.indexOf("items: [");
    let componentsEnd = "],";
    let componentsIndexEnd = data.indexOf(componentsEnd, componentsIndexStart);
    let componentsBlock = data.substring(componentsIndexStart, componentsIndexEnd);
    componentsBlock = `  
    ${componentsBlock}
    ${addMenu}
    `;
    data =
      data.substring(0, componentsIndexStart) +
      componentsBlock +
      data.substring(componentsIndexEnd);

    fs.writeFile(vitePressConfig, data, "utf8", err => {
      if (err) {
        console.error(`寫入文件失敗: ${err}`);
      } else {
        myLog(
          `${componentNameCn || "組件"}${componentName} 已成功添加到文檔庫菜單`,
          "docs/.vitepress/config.ts",
        );
      }
    });
  });
};

使用

經(jīng)過以上完成了組件創(chuàng)建腳本,這樣就不需要我們自己在修改一些文件了,直接編寫組件內(nèi)容、demo、組件文檔就可以了

在命令行中使用

npm run add table 表格
  • table 是組件的文件夾名稱和組件的name名稱
  • 表格 用來在說明文檔中展示和菜單顯示

組件名稱首字母無論是大寫還是小寫字母,在使用的時候都需要使用的時候都需要變成大寫字母

提交git

每次需要提交代碼的時候都需要執(zhí)行g(shù)it add .? 、git  commit -m ""? 、git push?
編寫一個腳本幫我們自動提交代碼

安裝依賴

npm  i child_process -D

在script?文件夾下面創(chuàng)建push.js?

/* eslint-disable no-undef */
// 導(dǎo)入Node.js的child_process模塊中的exec函數(shù),用于在子進程中執(zhí)行Shell命令
import { exec } from "child_process";
import { finish, warn } from "./tools.js";
// 這個異步函數(shù)接收一個命令字符串作為參數(shù),使用exec執(zhí)行該命令,并將其包裝成一個Promise。如果命令執(zhí)行成功,它會解析Promise并返回包含stdout和stderr的對象;如果執(zhí)行失敗,則拒絕Promise并返回錯誤。
const runCommand = command =>
  new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      if (error) {
        console.error(`exec error: ${error}`);
        reject(error);
      } else {
        resolve({ stdout, stderr });
      }
    });
  });

// 這是一個異步函數(shù),負責(zé)執(zhí)行一系列Git操作:添加所有改動、根據(jù)提供的或默認的提交信息進行提交、然后推送更改。它接受一個可選的commitMessage參數(shù),默認值為"新增組件"。
const main = async (commitMessage = "新增組件") => {
  try {
    await runCommand("git add .");
    const messageOption = commitMessage ? `-m "${commitMessage}"` : "";
    await runCommand(`git commit ${messageOption}`);
    await runCommand("git push");
    finish("代碼提交成功");
  } catch (error) {
    warn("Error during Git operations:", error);
  }
};

// 從命令行參數(shù)讀取提交信息
// 從Node.js進程的命令行參數(shù)中讀取信息。process.argv是一個數(shù)組,包含了啟動腳本的Node.js可執(zhí)行文件的路徑、腳本文件的路徑,以及之后的所有參數(shù)。slice(2)用來去掉前兩個元素,只保留實際傳入的參數(shù)。如果提供了參數(shù),它們會被連接成一個字符串作為提交信息,否則使用默認的"新增組件"。
const args = process.argv.slice(2);
const commitMessage = args.length > 0 ? args.join(" ") : "新增組件";

// 調(diào)用main函數(shù),并使用.catch處理任何在執(zhí)行過程中拋出的錯誤,錯誤信息會被打印到控制臺。
main(commitMessage).catch(console.error);

打包部署

對項目進行打包部署分為如下幾步:

  • 更改版本號
  • 打包npm
  • 切換鏡像源
  • 登錄鏡像源
  • 部署

在script?文件夾下賣弄創(chuàng)建npmPush.js?和npmPush?文件夾

更改版本號

在npmPush?文件夾下面創(chuàng)建bumpVersion.js?

// 修改版本號

import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { finish, warn } from "../tools.js";
export const bumpVersion = () => {
  // 當(dāng)前文件路徑
  const __filename = fileURLToPath(import.meta.url);
  // 當(dāng)前文件的目錄
  const __dirname = path.dirname(__filename);

  // 讀取package.json文件
  const packagePath = path.resolve(__dirname, "../../package.json");
  const packageJson = JSON.parse(fs.readFileSync(packagePath, "utf8"));
  // 原來的版本
  const originally = packageJson.version;

  // 分解版本號為數(shù)組,便于操作
  const versionParts = packageJson.version.split(".").map(Number);

  // 示例:遞增補丁版本號
  versionParts[2]++; // 假設(shè)是主版本.次版本.補丁版本的形式

  // 重新組合版本號
  packageJson.version = versionParts.join(".");

  // 將修改后的內(nèi)容寫回package.json
  fs.writeFileSync(packagePath, JSON.stringify(packageJson, null, 2), "utf8");

  finish(`版本更新成功: ${originally} --> ${packageJson.version}`, packagePath);
};

在script\npmPush.js?文件中引入

import { bumpVersion } from "./npmPush/bumpVersion.js";

bumpVersion();

打包組件庫

在npmPush?文件夾下面創(chuàng)建packNpm.js?

/* eslint-disable no-undef */
// 導(dǎo)入Node.js的child_process模塊中的exec函數(shù),用于在子進程中執(zhí)行Shell命令
import { finish, warn, runCommand } from "../tools.js";

export const packNpm = async () => {
  // 這是一個異步函數(shù),負責(zé)執(zhí)行一系列Git操作:添加所有改動、根據(jù)提供的或默認的提交信息進行提交、然后推送更改。它接受一個可選的commitMessage參數(shù),默認值為"新增組件"。
  try {
    await runCommand("npm run lib");
    finish("打包成功");
  } catch (error) {
    warn("打包發(fā)生錯誤:", error);
  }
};

在script\npmPush.js?文件中引入

import { bumpVersion } from "./npmPush/bumpVersion.js";
import { packNpm } from "./npmPush/packNpm.js";
const npmPush = async () => {
  await bumpVersion();
  await packNpm();
};

npmPush();

提交npm私庫

在npmPush?文件夾下面創(chuàng)建submitNpm.js?

/* eslint-disable no-undef */
import { finish, warn, runCommand } from "../tools.js";

export const submitNpm = async () => {
  try {
    await runCommand("npm publish");
    finish("推送成功");
    await runCommand("npm run push  '部署' ");
    finish("代碼提交成功");
  } catch (error) {
    warn("打包發(fā)生錯誤:", error);
  }
};

在script\npmPush.js?文件中引入

import { bumpVersion } from "./npmPush/bumpVersion.js";
import { packNpm } from "./npmPush/packNpm.js";
import { submitNpm } from "./npmPush/submitNpm.js";
const npmPush = async () => {
  await bumpVersion();
  await packNpm();
  await submitNpm();
};

npmPush();

總結(jié)

暫時先添加這三個腳本吧,需要注意的是:在打包部署之前需要登錄npm庫

在代碼中用到的tools.js?文件

/* eslint-disable no-undef */
// 導(dǎo)入Node.js的child_process模塊中的exec函數(shù),用于在子進程中執(zhí)行Shell命令
import { exec } from "child_process";
import ora from "ora";
// 首字母大寫
export const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
// 首字母轉(zhuǎn)小寫
export const lowerFirstLetter = str => str.charAt(0).toLowerCase() + str.slice(1);

// 打印
// 打印方法
export const myLog = function (text, path) {
  /* var black="\033[30m black \033[0m";
      var red="\033[31m red \033[0m";
      var green="\033[32m green \033[0m";
      var yellow="\033[33m yellow78979 \033[0m";
      var blue="\033[34m blue \033[0m";
      var popurse="\033[35m popurse \033[0m";
      var indigo="\033[36m indigo \033[0m";
      var white="\033[37m white \033[0m";
      var mix="\033[37;42m white \033[0m";
      console.log(black, red, green, yellow, blue, popurse, white);*/
  let popurse = "\x1b[32m 提示 \x1b[0m";
  process.stdout.write(popurse);
  let toolPathhint = "\x1b[34m " + text + " \x1b[0m";
  let toolPathPath = "\x1b[32m" + path + " \x1b[0m";
  console.log(toolPathhint, toolPathPath);
};

export const warn = function (text) {
  /* var black="\033[30m black \033[0m";
      var red="\033[31m red \033[0m";
      var green="\033[32m green \033[0m";
      var yellow="\033[33m yellow78979 \033[0m";
      var blue="\033[34m blue \033[0m";
      var popurse="\033[35m popurse \033[0m";
      var indigo="\033[36m indigo \033[0m";
      var white="\033[37m white \033[0m";
      var mix="\033[37;42m white \033[0m";
      console.log(black, red, green, yellow, blue, popurse, white);*/
  let popurse = "\x1b[31m 警告 \x1b[0m";
  process.stdout.write(popurse);
  let toolPathhint = "\x1b[31m " + text + " \x1b[0m";
  console.log(toolPathhint);
};
/**
 *
 * @param {string} text  輸出打印
 */
export const finish = function (text) {
  /* var black="\033[30m black \033[0m";
      var red="\033[31m red \033[0m";
      var green="\033[32m green \033[0m";
      var yellow="\033[33m yellow78979 \033[0m";
      var blue="\033[34m blue \033[0m";
      var popurse="\033[35m popurse \033[0m";
      var indigo="\033[36m indigo \033[0m";
      var white="\033[37m white \033[0m";
      var mix="\033[37;42m white \033[0m";
      console.log(black, red, green, yellow, blue, popurse, white);*/
  let popurse = "\x1b[35m 完成 \x1b[0m";
  process.stdout.write(popurse);
  let toolPathhint = "\x1b[36m " + text + " \x1b[0m";
  console.log(toolPathhint);
};

/**
 *
 * @param {String} command 需要執(zhí)行的命令
 * @returns
 */
export const runCommand = command => {
  let isGit = command.indexOf("git") === -1;

  let spinner;
  if (isGit) {
    spinner = ora(`開始執(zhí)行: "${command}"`).start();
  }
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      myLog("\n當(dāng)前命令:", command);
      if (error) {
        if (isGit) {
          spinner.fail(`exec error: ${error}`);
        }
        reject("error", error);
      } else {
        if (isGit) {
          // 打印命令的標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯誤,如果需要的話

          if (command === "npm run lib") {
            // spinner.succeed(`命令 "${command}" 執(zhí)行成功.`);
            console.log(`命令輸出: ${stdout}`);
            console.error(`stderr: ${stderr}`);
            finish("打包完成");
          } else if (command === "git push") {
            finish("代碼提交成功");
          } else if (command === "npm publish") {
            finish("npm庫推送成功");
          }
          spinner.succeed(`命令 "${command}" 執(zhí)行成功.`);

          resolve(true); // 命令成功執(zhí)行,    解決Promise
        } else {
          resolve({ stdout, stderr });
        }
      }
    });
  });
};

到此這篇關(guān)于vue3組件庫添加腳本的實現(xiàn)示例的文章就介紹到這了,更多相關(guān)vue3組件庫添加腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論