{"meta":{"title":"JavaScript アクションを作成する","intro":"このチュートリアルでは、アクション ツールキットを使って JavaScript アクションを構築する方法について説明します。","product":"GitHub Actions","breadcrumbs":[{"href":"/ja/actions","title":"GitHub Actions"},{"href":"/ja/actions/tutorials","title":"チュートリアル"},{"href":"/ja/actions/tutorials/create-actions","title":"アクションを作成する"},{"href":"/ja/actions/tutorials/create-actions/create-a-javascript-action","title":"JavaScript アクションを作成する"}],"documentType":"article"},"body":"# JavaScript アクションを作成する\n\nこのチュートリアルでは、アクション ツールキットを使って JavaScript アクションを構築する方法について説明します。\n\n## はじめに\n\nこのガイドでは、パッケージ化されたJavaScriptのアクションを作成して使うために必要な、基本的コンポーネントについて学びます。 アクションのパッケージ化に必要なコンポーネントのガイドに焦点を当てるため、アクションのコードの機能は最小限に留めます。 アクションでは、ログに \"Hello World\" が出力されます。カスタム名を指定した場合は \"Hello \\[who-to-greet]\" が出力されます。\n\nこのガイドでは、開発の速度を高めるためにGitHub Actions ToolkitのNode.jsモジュールを使います。 詳細については、[actions/toolkit](https://github.com/actions/toolkit) リポジトリを参照してください。\n\nこのプロジェクトを完了すると、JavaScript アクションを構築し、ワークフローでテストする方法を理解できるようになります。\n\nJavaScriptのアクションがGitHubがホストするすべてのランナー（Ubuntu、Windows、macOS）と互換性があることを保証するためには、作成するパッケージ化されたJavaScriptのコードは純粋なJavaScriptであり、他のバイナリに依存していてはなりません。 JavaScript のアクションはランナー上で直接実行され、ランナー イメージ内に既に存在するバイナリを利用します。\n\nデータ 再利用可能なアクション.コンテキスト挿入警告 %}\n\n## 前提条件\n\n開始する前に、Node.jsをダウンロードし、パブリック GitHub リポジトリを作成する必要があります。\n\n1. Node.js 20.x (これには、npm も含まれます) をダウンロードしてインストールします。\n\n   <https://nodejs.org/en/download/>\n\n2. GitHub 上に新しいパブリック リポジトリを作成し、それを \"hello-world-javascript-action\" と呼びます。 詳しくは、「[新しいリポジトリの作成](/ja/repositories/creating-and-managing-repositories/creating-a-new-repository)」をご覧ください。\n\n3. リポジトリをお手元のコンピューターにクローンします。 詳しくは、「[リポジトリをクローンする](/ja/repositories/creating-and-managing-repositories/cloning-a-repository)」をご覧ください。\n\n4. ターミナルから、ディレクトリを新しいリポジトリに変更します。\n\n   ```shell copy\n   cd hello-world-javascript-action\n   ```\n\n5. ターミナルから、npm を使用してディレクトリを初期化し、`package.json` ファイルを生成します。\n\n   ```shell copy\n   npm init -y\n   ```\n\n## アクションのメタデータファイルの作成\n\n次のコード例を使用して、`action.yml` という名前の新しいファイルを `hello-world-javascript-action` ディレクトリに作成します。 詳しくは、「[メタデータ構文リファレンス](/ja/actions/creating-actions/metadata-syntax-for-github-actions)」をご覧ください。\n\n```yaml copy\nname: Hello World\ndescription: Greet someone and record the time\n\ninputs:\n  who-to-greet: # id of input\n    description: Who to greet\n    required: true\n    default: World\n\noutputs:\n  time: # id of output\n    description: The time we greeted you\n\nruns:\n  using: node20\n  main: dist/index.js\n```\n\nこのファイルによって、`who-to-greet` 入力と `time` 出力が定義されます。 また、アクションのランナーに対して、この JavaScript アクションの実行を開始する方法を伝えています。\n\n## アクションツールキットのパッケージの追加\n\nアクションのツールキットは、Node.js パッケージのコレクションで、より一貫性を保ちつつ、JavaScript を素早く作成するためのものです。\n\nツールキット [`@actions/core`](https://github.com/actions/toolkit/tree/main/packages/core) パッケージには、ワークフロー コマンド、入力および出力変数、終了ステータス、デバッグ メッセージに対するインターフェイスが用意されています。\n\nツールキットには、認証された Octokit REST クライアントとGitHub Actions コンテキストへのアクセスを返す [`@actions/github`](https://github.com/actions/toolkit/tree/main/packages/github) パッケージも用意されています。\n\nこのツールキットは、`core` および `github` パッケージ以外のものも備えています。 詳細については、[actions/toolkit](https://github.com/actions/toolkit) リポジトリを参照してください。\n\nご利用のターミナルで、アクション ツールキットの `core` および `github` パッケージをインストールします。\n\n```shell copy\nnpm install @actions/core @actions/github\n```\n\n```\n          `node_modules` ディレクトリと、インストールされている依存関係とそのバージョンを追跡する `package-lock.json` ファイルが表示されます。 \n          `node_modules` ディレクトリをリポジトリにコミットしないでください。\n```\n\n## アクションのコードの記述\n\nこのアクションは、ツールキットを使って、アクションのメタデータ ファイルに必要な `who-to-greet` 入力変数を取得し、ログのデバッグメッセージに \"Hello \\[who-to-greet]\" を出力します。 次に、スクリプトは現在の時刻を取得し、それをジョブ内で後に実行するアクションが利用できる出力変数に設定します。\n\nGitHub Actions、webhook イベント、Git refs、ワークフロー、アクション、およびワークフローをトリガーしたユーザーに関するコンテキスト情報を提供します。 コンテキスト情報にアクセスするために、`github` パッケージを利用できます。 あなたの書くアクションが、webhook イベントペイロードをログに出力します。\n\n次のコードを含む `src/index.js` という名前の新しいファイルを追加します。\n\n```javascript copy\nimport * as core from \"@actions/core\";\nimport * as github from \"@actions/github\";\n\ntry {\n  // `who-to-greet` input defined in action metadata file\n  const nameToGreet = core.getInput(\"who-to-greet\");\n  core.info(`Hello ${nameToGreet}!`);\n\n  // Get the current time and set it as an output variable\n  const time = new Date().toTimeString();\n  core.setOutput(\"time\", time);\n\n  // Get the JSON webhook payload for the event that triggered the workflow\n  const payload = JSON.stringify(github.context.payload, undefined, 2);\n  core.info(`The event payload: ${payload}`);\n} catch (error) {\n  core.setFailed(error.message);\n}\n```\n\n上記の `index.js` の例でエラーがスローされた場合、`core.setFailed(error.message);` では、アクション ツールキットの [`@actions/core`](https://github.com/actions/toolkit/tree/main/packages/core) パッケージを使用してメッセージをログに記録し、失敗した終了コードを設定します。 詳しくは、「[アクションの終了コードの設定](/ja/actions/creating-actions/setting-exit-codes-for-actions)」をご覧ください。\n\n## READMEの作成\n\nアクションの使用方法を説明するために、README ファイルを作成できます。 README はアクションの公開を計画している時に非常に役立ちます。また、アクションの使い方をあなたやチームが覚えておく方法としても優れています。\n\n```\n          `hello-world-javascript-action` ディレクトリに、次の情報を指定する `README.md` ファイルを作成します。\n```\n\n* アクションの動作に関する詳細な説明。\n* 必須の入力および出力の引数。\n* 省略可能な入力および出力の引数。\n* アクションで使用されるシークレット。\n* アクションで使用される環境変数。\n* ワークフローでのアクションの使用方法の例。\n\n````markdown copy\n# Hello world JavaScript action\n\nThis action prints \"Hello World\" or \"Hello\" + the name of a person to greet to the log.\n\n## Inputs\n\n### `who-to-greet`\n\n**Required** The name of the person to greet. Default `\"World\"`.\n\n## Outputs\n\n### `time`\n\nThe time we greeted you.\n\n## Example usage\n\n```yaml\nuses: actions/hello-world-javascript-action@e76147da8e5c81eaf017dede5645551d4b94427b\nwith:\n  who-to-greet: Mona the Octocat\n```\n````\n\n## アクションをコミットし、タグを付けて、プッシュする\n\nGitHub を使うと、実行時にワークフローで実行される各アクションをダウンロードし、コードの完全なパッケージとして実行できます。その後は、`run` などのワークフロー コマンドを使ってランナー マシンを操作できるようになります。 つまり、JavaScript コードを実行するために必要なあらゆる依存関係を含める必要があります。 たとえば、このアクションでは `@actions/core` と `@actions/github` パッケージが使われます。\n\n```\n          `node_modules` ディレクトリをチェックインすると、問題が発生する可能性があります。 別の方法として、[`rollup.js`](https://github.com/rollup/rollup) や [`@vercel/ncc`](https://github.com/vercel/ncc) などのツールを使って、配布用の 1 つのファイルにコードと依存関係を結合できます。\n```\n\n1. ターミナルで次のコマンドを実行して、`rollup` とそのプラグインをインストールします。\n\n   `npm install --save-dev rollup @rollup/plugin-commonjs @rollup/plugin-node-resolve`\n\n2. 次のコードを使って、リポジトリのルートに `rollup.config.js` という名前の新しいファイルを作成します。\n\n   ```javascript copy\n   import commonjs from \"@rollup/plugin-commonjs\";\n   import { nodeResolve } from \"@rollup/plugin-node-resolve\";\n\n   const config = {\n     input: \"src/index.js\",\n     output: {\n       esModule: true,\n       file: \"dist/index.js\",\n       format: \"es\",\n       sourcemap: true,\n     },\n     plugins: [commonjs(), nodeResolve({ preferBuiltins: true })],\n   };\n\n   export default config;\n   ```\n\n3. ご利用の `dist/index.js` ファイルをコンパイルします。\n\n   `rollup --config rollup.config.js`\n\n   ご自分のコードとすべての依存関係を含む新しい `dist/index.js` ファイルが表示されます。\n\n4. ターミナルから更新をコミットします。\n\n   ```shell copy\n   git add src/index.js dist/index.js rollup.config.js package.json package-lock.json README.md action.yml\n   git commit -m \"Initial commit of my first action\"\n   git tag -a -m \"My first action release\" v1.1\n   git push --follow-tags\n   ```\n\nコードをコミットしてプッシュすると、更新されたリポジトリは次のようになります。\n\n```text\nhello-world-javascript-action/\n├── action.yml\n├── dist/\n│   └── index.js\n├── package.json\n├── package-lock.json\n├── README.md\n├── rollup.config.js\n└── src/\n    └── index.js\n```\n\n## ワークフローでアクションをテストする\n\nこれで、ワークフローでアクションをテストできるようになりました。\n\nパブリック アクションは、任意のリポジトリ内のワークフローで使用できます。 アクションがプライベート  リポジトリ内にある場合、リポジトリ設定は、同じリポジトリ内でのみ、または同じ  ユーザーまたは組織  が所有する他のリポジトリでもアクションが可能かどうかによって決まります。 詳しくは、「[リポジトリのGitHub Actions設定の管理](/ja/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository)」をご覧ください。\n\n### パブリックアクションを使用する例\n\nこの例では、外部リポジトリ内から新しいパブリック アクションを実行する方法を示します。\n\n次の YAML を `.github/workflows/main.yml` にある新しいファイルにコピーし、ユーザー名と上記で作成したパブリック リポジトリの名前で `uses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b` 行を更新します。\n`who-to-greet` 入力を自分の名前に置き換えることもできます。\n\n```yaml copy\non:\n  push:\n    branches:\n      - main\n\njobs:\n  hello_world_job:\n    name: A job to say hello\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Hello world action step\n        id: hello\n        uses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b\n        with:\n          who-to-greet: Mona the Octocat\n\n      # Use the output from the `hello` step\n      - name: Get the output time\n        run: echo \"The time was ${{ steps.hello.outputs.time }}\"\n```\n\nこのワークフローがトリガーされると、ランナーによってパブリック リポジトリから `hello-world-javascript-action` アクションがダウンロードされ、そして実行されます。\n\n### プライベートアクションを使用する例\n\nワークフロー コードをアクションのリポジトリ内の `.github/workflows/main.yml` ファイルにコピーします。\n`who-to-greet` 入力を自分の名前に置き換えることもできます。\n\n```yaml copy\non:\n  push:\n    branches:\n      - main\n\njobs:\n  hello_world_job:\n    name: A job to say hello\n    runs-on: ubuntu-latest\n\n    steps:\n      # To use this repository's private action,\n      # you must check out the repository\n      - name: Checkout\n        uses: actions/checkout@v6\n\n      - name: Hello world action step\n        uses: ./ # Uses an action in the root directory\n        id: hello\n        with:\n          who-to-greet: Mona the Octocat\n\n      # Use the output from the `hello` step\n      - name: Get the output time\n        run: echo \"The time was ${{ steps.hello.outputs.time }}\"\n```\n\nリポジトリから **\\[アクション]** タブをクリックして、最新のワークフロー実行を選択します。 **\\[ジョブ]** または視覚化グラフで、\"**A job to say hello**\" をクリックします。\n\n**Hello world action step** をクリックすると、\"Hello Mona the Octocat\" またはログに出力されている `who-to-greet` に入力した名前が表示されます。 タイムスタンプを表示するには、 **\\[出力時刻の取得]** をクリックします。\n\n## JavaScript アクションを作成するためのテンプレート リポジトリ\n\nGitHub には、JavaScript および TypeScript アクションを作成するためのテンプレート リポジトリが用意されています。 これらのテンプレートを使い、テスト、リンティング、その他の推奨プラクティスなど、新しいアクションの作成をすぐに始められます。\n\n* [\n  `javascript-action` テンプレート リポジトリ](https://github.com/actions/javascript-action)\n* [\n  `typescript-action` テンプレート リポジトリ](https://github.com/actions/typescript-action)\n\n## GitHub.com\n\nに対する JavaScript アクションの例\n\nJavaScript のアクション例は、GitHub.com\nに多数あります。\n\n* [DevExpress/testcafe-action](https://github.com/DevExpress/testcafe-action)\n* [duckduckgo/privacy-configuration](https://github.com/duckduckgo/privacy-configuration)"}