ホームページ  >  記事  >  ウェブフロントエンド  >  なぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明

なぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明

青灯夜游
青灯夜游転載
2023-04-10 19:06:061324ブラウズ

なぜ足場が必要なのでしょうか?足場はどうやって建てるの?以下の記事でノード上に足場を構築する手順を紹介していますので、皆様のお役に立てれば幸いです。

なぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明

1 スキャフォールディングが必要な理由

  • 対話に基づいてプロジェクト構造と構成ファイルを動的に生成します。
  • ユーザーはコマンド操作を通じてさまざまなテンプレートをダウンロードします
  • テンプレート エンジンを通じてカスタム プロジェクト テンプレートをレンダリングします
  • テンプレートが変更された場合、テンプレートを更新するだけでよく、ユーザーはテンプレートを更新する必要があります。スキャフォールディングを更新する必要はありません [関連チュートリアルの推奨事項: nodejs ビデオ チュートリアル プログラミング教育 ]

2 構築手順

  • 新しい mycli フォルダーを作成し (ファイル名はカスタマイズ可能)、その下に新しい bin ファイルを作成し、新しい bin を作成します ファイル index.js、この index.js がエントリ ファイルであり、index.js がファイル # のヘッダーに追加されます!/usr/bin/env nodecode

  • package.json ファイルを生成します。この時点で、bin 構成オブジェクトが存在します。キー値はグローバル スキャフォールディング名、値はエントリ ファイル bin ファイルの index.jspath です。

    npm init -y
    npm install

  • #スキャフォールディング グローバル コマンドをグローバル コマンドにリンクします。ターミナルに mycli が出力された場合、リンクは成功しました。

    //命令可以将一个任意位置的npm包链接到全局执行环境,从而在任意位置使用命令行都可以直接运行该npm包。
    npm link
  • インストールの依存関係

  npm install commander inquirer@8.2.5 download-git-repo chalk@4.1.2 ora@5.4.1 figlet handlebars
  • commander: コマンド ライン ツール。これを使用して、コマンド ライン コマンドを実行し、ユーザーが何をしたいのかを把握する
  • #inquirer: ユーザーに美しいインターフェイスと質問する方法を提供する対話型コマンド ライン ツール
  • download-git-repo
  • : リモート ウェアハウスのテンプレート プロジェクトのダウンロードを担当するリモート テンプレート ツールをダウンロードします。
  • chalk
  • : カラー プラグイン。コマンド ライン出力スタイル。情報ログとエラー ログは色で区別され、明確で直感的です。
  • ora
  • : フロントのローディング効果と同様に、ローディング効果を表示するために使用されます。終了ページ。テンプレートのダウンロードなどの時間のかかる操作に使用します。読み込み効果により、ユーザーは進行中です、しばらくお待ちくださいというメッセージを表示できます。
  • figlet
  • : 中抜きフォント スタイル
  • 注: 以下のコードは bin ファイルに配置されます
index.js

デバッグ2.1 Commander.js

の概要Commander.js

は、ノードのコマンド ライン プログラムを構築するために使用されるツールであり、カスタム命令を使用してグローバル コマンド ラインでノード スクリプトを実行できるようになります。当初は、スクリプトが配置されているファイルのルート ディレクトリにある node xxx.js を介してのみスクリプトを実行できましたが、コマンダーを使用してコマンド ライン プログラムをビルドした後は、任意のディレクトリで直接実行できるようになります。デスクトップなど、ユーザー ディレクトリなど、カスタム コマンドを入力してスクリプトを直接実行するほうが簡単です。 <pre class="brush:js;toolbar:false;">#!/usr/bin/env node //就是解决了不同的用户node路径不同的问题,可以让系统动态的去查找node来执行你的脚本文件。 //node.js内置了对命令行操作的支持,在 package.json 中的 bin 字段可以定义命令名和关联的执行文件。 const program = require(&quot;commander&quot;) program.version(&amp;#39;1.1.0&amp;#39;) function getFramwork (val) { console.log(val); } const myhelp = function (program) { program.option(&amp;#39;-f --framwork &lt;framwork&gt;&amp;#39;, &amp;#39;设置框架&amp;#39;, getFramwork) } const createProgress = function (program) { program.command(&amp;#39;create &lt;progress&gt; [other...]&amp;#39;) .alias(&amp;#39;crt&amp;#39;) .description(&amp;#39;创建项目&amp;#39;) .action((progress, arg) =&gt; { console.log(progress, arg); }) } myhelp(program); createProgress(program); program.parse(process.argv) // 补充 .parse() // 作用就是解析,参数就是要解析的字符串,一般使用时参数就是用process.argv,就是用户输入参数</pre>グローバル コマンド

mycli

を実行してすべてのコマンドを出力します~~

##2.2 download-git-repoなぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明

download
    (リポジトリ、宛先、オプション、コールバック)
  • repository
  • :ダウンロードアドレス
  • destination
  • : ダウンロードpath
  • options
  • : 設定項目 {clone: true}
  • callback
  • : ダウンロード後のコールバック
  • <pre class="brush:js;toolbar:false;">#!/usr/bin/env node const download = require(&amp;#39;download-git-repo&amp;#39;); download(&amp;#39;direct:https://gitlab.com/flippidippi/download-git-repo-fixture.git&amp;#39;, &quot;xxx&quot;, { clone: true }, (err) =&gt; { console.log(err ? &amp;#39;Error&amp;#39; : &amp;#39;Success&amp;#39;) })</pre>
  • mycli
を実行すると、

## ファイルの下に xxx

ファイルが生成されます。2.3 Inquirer (コマンド インタラクション)

なぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明

inquirer

は、一般的に使用される対話型端末ユーザー インターフェイスのコレクションです。簡単に言うと、

inquirer

は、端末のさまざまな対話動作を簡単に実行できるようにするライブラリです。 inquirer は主に、質問の登録を容易にする 3 つのメソッドを提供します。

prompt(questions) => Promise

このメソッドは、端末対話の中核となるメソッドです。プロンプト メソッドは、端末に対話型コマンド インターフェイスを開始するように指示します。 - プロンプト メソッドは、
    questions
  • の配列を渡す必要があります。questions 配列には、オブジェクトの形式で各質問が含まれています。question の特定の構造フィールドの意味については、後で紹介します。 - プロンプト メソッドの戻り値は Promise オブジェクトで、promise.then が受け取る戻り値は answers オブジェクトです。answer オブジェクトには、以前のすべての質問に対する回答のデータ結果が含まれます。
    #!/usr/bin/env node
    const inquirer = require("inquirer")
    function getUsername() {
      return inquirer
        .prompt([
          {
            type: "input",
            name: "progress",
            message: "请输入项目名称",
            default: "progress",
            filter(input) {
              return input.trim()
            },
            validate(input) {
              return input.length > 0
            },
          },
        ])
        .then((answer) => {
          console.log(answer)
        })
    }
    function getFramework() {
      return inquirer
        .prompt([
          {
            type: "list",
            name: "framework",
            choices: [
              "express",
              new inquirer.Separator(),
              "koa",
              new inquirer.Separator(),
              "egg",
            ],
            message: "请选择你所使用的框架",
          },
        ])
        .then((answer) => {
          console.log(answer)
        })
    }
    
    function getSelect() {
      return inquirer
        .prompt([
          {
            type: "checkbox",
            name: "userndasde",
            choices: [
              { name: "pr", disabled: true },
              { name: "oa", checked: true },
              "gg",
            ],
            message: "需要的验证格式",
            // default: ["oa"],
          },
        ])
        .then((answer) => {
          console.log(answer)
        })
    }
    async function init() {
      await getSelect()
      await getUsername()
      await getFramework()
    }
    init()
    2.4 ora とチョーク (美化)
  • ユーザーが回答を入力すると、テンプレートのダウンロードが開始されます。このとき、
ora

が使用されます。ダウンロードが進行中であることをユーザーに通知します。

注: バージョンによって導入方法が異なることに注意してください。ここでは、ora (バージョン 5.4.1)、

chalk

(バージョン 4.1.2) を使用します。<pre class="brush:js;toolbar:false;">const ora = require(&quot;ora&quot;) const chalk = require(&quot;chalk&quot;) const spinner = ora(&quot;Loading unicorns&quot;).start() spinner.text = chalk.blue(&quot;下载中~~~~~~&quot;) setTimeout(() =&gt; { spinner.succeed(chalk.red(&quot;下载成功!&quot;)) spinner.fail(&quot;下载失败!&quot;) spinner.warn(&quot;警告!&quot;) }, 2000)</pre><h4 data-id="heading-7">2.5 figlet(镂空文字)</h4> <p>镂空文字调试器地址:<a href="https://www.php.cn/link/47f91db40efc6a22350eca5c953c4742" target="_blank" title="http://patorjk.com/software/taag/" ref="nofollow noopener noreferrer">地址</a></p> <p><code>figlet旨在完全实现JavaScript中的FIGfont规范。它可以在浏览器和Node.js中工作。

用法

figlet.text( description,{options},callback(err,data){}) 这个是异步的会被

参数

  • description:需要格式化的字符串

  • options:参数配置

    • Font:字体,Default value:Standard
    • horizontalLayout:布局,Default value:default; Values:{default,full,fitted};
    • verticalLayout:垂直布局, Default value:default; Values:{defalut,full,fitted,controlled smushing,universal smushing};
    • Width:宽度;
    • whitespaceBreak:换行(Boolean); Default value:false
  • callback(err,data):回调

const figlet = require("figlet")
const chalk = require("chalk")
//简单函数
function handleAsync(params) {
  const JAVASCRIPT = figlet.textSync(
    "NODEJS",
    {
      font: "big",
      horizontalLayout: "fitted",
      verticalLayout: "controlled smushing",
      width: 600,
      whitespaceBreak: true,
    },
    function (err, data) {
      if (err) {
        console.log("Something went wrong...")
        console.dir(err)
        return
      }
      console.log(data)
    }
  )

  console.log(chalk.blue.bold(JAVASCRIPT))
}
handleAsync()

なぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明

总结

创建一个完整的脚手架

目录结构:

  • bin/index.js
#!/usr/bin/env node
console.log("adas");
require("../lib/commander/index.js")
  • lib/commonder/index.js
const program = require("commander")
const init = require(&#39;../inquirer/index&#39;);
const downloadFun = require("../core/download.js");
program.version(&#39;1.1.0&#39;)
function getFramwork (val) {
  console.log(val);
}
const myhelp = function (program) {
  program.option(&#39;-f --framwork <framork> [other...]&#39;, &#39;设置框架&#39;, getFramwork)
}
const createProgress = function (program) {
  program.command(&#39;create <progress> [other...]&#39;)
    .alias(&#39;crt&#39;)
    .description(&#39;创建项目&#39;)
    .action((progress, arg) => {
      init();
    })
}
const downloadUrl = function (program) {
  program.command(&#39;download <url> [...other]&#39;)
    .description(&#39;下载内容&#39;)
    .action((url, ...args) => {
      console.log(args);
      downloadFun(url, args[1].args[1])
    })
}
myhelp(program);
downloadUrl(program);
createProgress(program)
program.parse(process.argv)
  • lib/core/action.js (package.json重写)
const fs = require(&#39;fs&#39;);
const path = require("path");
const handlebars = require("handlebars");
  function modifyPackageJson (options) {
    let downloadPath = options.projectName;
    const packagePath = path.join(downloadPath, &#39;package.json&#39;);
    console.log(packagePath, "packagePath");
    
    //判断是否存在package.json文件
    if (fs.existsSync(packagePath)) {
      let content = fs.readFileSync(packagePath).toString();
      
      //判断是否选择了eslint
      if (options.isIslint) {
        let targetContent = JSON.parse(content);
        content = JSON.stringify(targetContent);
        targetContent.dependencies.eslint = "^1.0.0";
        console.log("content", content);
      }
      
      //写入模板
      const template = handlebars.compile(content);
      const param = { name: options.projectName };
      const result = template(param);
      
      //重新写入package.json文件
      fs.writeFileSync(packagePath, result);
      console.log(&#39;modify package.json complate&#39;);
    } else {
      throw new Error(&#39;no package.json&#39;);
    }
  }
  module.exports = modifyPackageJson
  • lib/core/download.js
  const download = require(&#39;download-git-repo&#39;);
  const ora = require("ora");
  const chalk = require("chalk");
  const figlet = require("figlet");
  const modifyPackageJson = require("./action")
  
  function handleAsync (params) {
    const JAVASCRIPT = figlet.textSync(&#39;JAVASCRIPT&#39;, {
      font: &#39;big&#39;,
      horizontalLayout: &#39;fitted&#39;,
      verticalLayout: &#39;controlled smushing&#39;,
      width: 600,
      whitespaceBreak: true
    }, function (err, data) {
      if (err) {
        console.log(&#39;Something went wrong...&#39;);
        console.dir(err);
        return;
      }
      console.log(data);
    });
    console.log(chalk.blue.bold(JAVASCRIPT));
  }
  
  const downloadFun = (url, option) => {
    const spinner = ora("Loading unicorns").start()
    spinner.text = chalk.blue("下载中");
    
    download(url, option.projectName, { clone: true }, function (err) {
      if (err) {
        spinner.fail("下载失败!");
        handleAsync()
      } else {
        spinner.succeed(chalk.red("下载成功!"))
        console.log(chalk.blue(`cd ${option.projectName}`))
        console.log(chalk.red("npm install"))
        console.log(chalk.yellow(`npm run dev`))
        modifyPackageJson(option)
        handleAsync()
      }
    })
  }
  module.exports = downloadFun;
  • inquire/index.js 注意frameworkConfig写自己的gitlab仓库地址
  const inquirer = require("inquirer");
  const downloadFun = require("../core/download.js");
  const frameworkConfig = {
    front: "https://gitlab.com/flippidippi/download-git-repo-fixture.git",
    manager: "https://gitlab.com/flippidippi/download-git-repo-fixture.git"
  }
  const config = {};
  
  function getFramework () {
    return inquirer.prompt([
      {
        type: &#39;list&#39;,
        name: &#39;framework&#39;,
        choices: ["front", "manager"],
        message: "请选择你所使用的框架"
      }
    ]).then((answer) => {
      return answer.framework;
    })
  }
  
  function getProjectName () {
    return inquirer.prompt([
      {
        type: &#39;input&#39;,
        name: &#39;projectName&#39;,
        message: &#39;项目名称&#39;,
        filter (input) {
          return input.trim();
        },
      }
    ]).then((answer) => {
      console.log(answer, "FDsfs");
      return answer.projectName;
    })
  }
  
  function getIsEslint () {
    return inquirer.prompt([
      {
        type: &#39;confirm&#39;,
        name: &#39;isIslint&#39;,
        message: &#39;是否使用eslint校验格式?&#39;
      }
    ]).then((answer) => {
      return answer.isIslint;
    })
  }
  
  async function init () {
    config.projectName = await getProjectName();
    config.framework = await getFramework();
    config.isIslint = await getIsEslint();
    let url = config.framework == "front" ? frameworkConfig.front : frameworkConfig.manager;
    downloadFun("direct:" + url, config);
  }
  module.exports = init;

更多node相关知识,请访问:nodejs 教程

以上がなぜ足場が必要なのでしょうか?ノードに足場を構築する手順の詳細な説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はjuejin.cnで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。