Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
GitHub Docs

Creating a JavaScript action

In this tutorial, you'll learn how to build a JavaScript action using the actions toolkit.

Introduction

In this guide, you'll learn about the basic components needed to create and use a packaged JavaScript action. To focus this guide on the components needed to package the action, the functionality of the action's code is minimal. The action prints "Hello World" in the logs or "Hello [who-to-greet]" if you provide a custom name.

This guide uses the GitHub Actions Toolkit Node.js module to speed up development. For more information, see theactions/toolkit repository.

Once you complete this project, you should understand how to build your own JavaScript action and test it in a workflow.

To ensure your JavaScript actions are compatible with all GitHub-hosted runners (Ubuntu, Windows, and macOS), the packaged JavaScript code you write should be pure JavaScript and not rely on other binaries. JavaScript actions run directly on the runner and use binaries that already exist in the runner image.

Warning

When creating workflows and actions, you should always consider whether your code might execute untrusted input from possible attackers. Certain contexts should be treated as untrusted input, as an attacker could insert their own malicious content. For more information, seeSecure use reference.

Prerequisites

Before you begin, you'll need to download Node.js and create a public GitHub repository.

  1. Download and install Node.js 20.x, which includes npm.

    https://nodejs.org/en/download/

  2. Create a new public repository on GitHub and call it "hello-world-javascript-action". For more information, seeCreating a new repository.

  3. Clone your repository to your computer. For more information, seeCloning a repository.

  4. From your terminal, change directories into your new repository.

    Shell
    cd hello-world-javascript-action
  5. From your terminal, initialize the directory with npm to generate apackage.json file.

    Shell
    npm init -y

Creating an action metadata file

Create a new file namedaction.yml in thehello-world-javascript-action directory with the following example code. For more information, seeMetadata syntax reference.

YAML
name:HelloWorlddescription:Greetsomeoneandrecordthetimeinputs:who-to-greet:# id of inputdescription:Whotogreetrequired:truedefault:Worldoutputs:time:# id of outputdescription:Thetimewegreetedyouruns:using:node20main:dist/index.js

This file defines thewho-to-greet input andtime output. It also tells the action runner how to start running this JavaScript action.

Adding actions toolkit packages

The actions toolkit is a collection of Node.js packages that allow you to quickly build JavaScript actions with more consistency.

The toolkit@actions/core package provides an interface to the workflow commands, input and output variables, exit statuses, and debug messages.

The toolkit also offers a@actions/github package that returns an authenticated Octokit REST client and access to GitHub Actions contexts.

The toolkit offers more than thecore andgithub packages. For more information, see theactions/toolkit repository.

At your terminal, install the actions toolkitcore andgithub packages.

Shell
npm install @actions/core @actions/github

You should now see anode_modules directory and apackage-lock.json file which track any installed dependencies and their versions. You should not commit thenode_modules directory to your repository.

Writing the action code

This action uses the toolkit to get thewho-to-greet input variable required in the action's metadata file and prints "Hello [who-to-greet]" in a debug message in the log. Next, the script gets the current time and sets it as an output variable that actions running later in a job can use.

GitHub Actions provide context information about the webhook event, Git refs, workflow, action, and the person who triggered the workflow. To access the context information, you can use thegithub package. The action you'll write will print the webhook event payload to the log.

Add a new file calledsrc/index.js, with the following code.

JavaScript
import *as corefrom"@actions/core";import *as githubfrom"@actions/github";try {// `who-to-greet` input defined in action metadata fileconst nameToGreet = core.getInput("who-to-greet");  core.info(`Hello${nameToGreet}!`);// Get the current time and set it as an output variableconst time =newDate().toTimeString();  core.setOutput("time", time);// Get the JSON webhook payload for the event that triggered the workflowconst payload =JSON.stringify(github.context.payload,undefined,2);  core.info(`The event payload:${payload}`);}catch (error) {  core.setFailed(error.message);}

If an error is thrown in the aboveindex.js example,core.setFailed(error.message); uses the actions toolkit@actions/core package to log a message and set a failing exit code. For more information, seeSetting exit codes for actions.

Creating a README

To let people know how to use your action, you can create a README file. A README is most helpful when you plan to share your action publicly, but is also a great way to remind you or your team how to use the action.

In yourhello-world-javascript-action directory, create aREADME.md file that specifies the following information:

  • A detailed description of what the action does.
  • Required input and output arguments.
  • Optional input and output arguments.
  • Secrets the action uses.
  • Environment variables the action uses.
  • An example of how to use your action in a workflow.
Markdown
# Hello world JavaScript actionThis action prints "Hello World" or "Hello" + the name of a person to greet to the log.## Inputs### `who-to-greet`**Required** The name of the person to greet. Default`"World"`.## Outputs### `time`The time we greeted you.## Example usage```yamluses: actions/hello-world-javascript-action@e76147da8e5c81eaf017dede5645551d4b94427bwith:  who-to-greet: Mona the Octocat```

Commit, tag, and push your action

GitHub downloads each action run in a workflow during runtime and executes it as a complete package of code before you can use workflow commands likerun to interact with the runner machine. This means you must include any package dependencies required to run the JavaScript code. For example, this action uses@actions/core and@actions/github packages.

Checking in yournode_modules directory can cause problems. As an alternative, you can use tools such asrollup.js or@vercel/ncc to combine your code and dependencies into one file for distribution.

  1. Installrollup and its plugins by running this command in your terminal.

    npm install --save-dev rollup @rollup/plugin-commonjs @rollup/plugin-node-resolve

  2. Create a new file calledrollup.config.js in the root of your repository with the following code.

    JavaScript
    import commonjsfrom"@rollup/plugin-commonjs";import { nodeResolve }from"@rollup/plugin-node-resolve";const config = {input:"src/index.js",output: {esModule:true,file:"dist/index.js",format:"es",sourcemap:true,  },plugins: [commonjs(),nodeResolve({preferBuiltins:true })],};exportdefault config;
  3. Compile yourdist/index.js file.

    rollup --config rollup.config.js

    You'll see a newdist/index.js file with your code and any dependencies.

  4. From your terminal, commit the updates.

    Shell
    git add src/index.js dist/index.js rollup.config.js package.json package-lock.json README.md action.ymlgit commit -m "Initial commit of my first action"git tag -a -m "My first action release" v1.1git push --follow-tags

When you commit and push your code, your updated repository should look like this:

hello-world-javascript-action/├── action.yml├── dist/│   └── index.js├── package.json├── package-lock.json├── README.md├── rollup.config.js└── src/    └── index.js

Testing out your action in a workflow

Now you're ready to test your action out in a workflow.

Public actions can be used by workflows in any repository. When an action is in a private repository, the repository settings dictate whether the action is available only within the same repository or also to other repositories owned by the same user or organization. For more information, seeManaging GitHub Actions settings for a repository.

Example using a public action

This example demonstrates how your new public action can be run from within an external repository.

Copy the following YAML into a new file at.github/workflows/main.yml, and update theuses: octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b line with your username and the name of the public repository you created above. You can also replace thewho-to-greet input with your name.

YAML
on:push:branches:-mainjobs:hello_world_job:name:Ajobtosayhelloruns-on:ubuntu-lateststeps:-name:Helloworldactionstepid:hellouses:octocat/hello-world-javascript-action@1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0bwith:who-to-greet:MonatheOctocat# Use the output from the `hello` step-name:Gettheoutputtimerun:echo"The time was ${{ steps.hello.outputs.time }}"

When this workflow is triggered, the runner will download thehello-world-javascript-action action from your public repository and then execute it.

Example using a private action

Copy the workflow code into a.github/workflows/main.yml file in your action's repository. You can also replace thewho-to-greet input with your name.

YAML
on:push:branches:-mainjobs:hello_world_job:name:Ajobtosayhelloruns-on:ubuntu-lateststeps:# To use this repository's private action,# you must check out the repository-name:Checkoutuses:actions/checkout@v4-name:Helloworldactionstepuses:./# Uses an action in the root directoryid:hellowith:who-to-greet:MonatheOctocat# Use the output from the `hello` step-name:Gettheoutputtimerun:echo"The time was ${{ steps.hello.outputs.time }}"

From your repository, click theActions tab, and select the latest workflow run. UnderJobs or in the visualization graph, clickA job to say hello.

ClickHello world action step, and you should see "Hello Mona the Octocat" or the name you used for thewho-to-greet input printed in the log. To see the timestamp, clickGet the output time.

Template repositories for creating JavaScript actions

GitHub provides template repositories for creating JavaScript and TypeScript actions. You can use these templates to quickly get started with creating a new action that includes tests, linting, and other recommended practices.

Example JavaScript actions on GitHub.com

You can find many examples of JavaScript actions on GitHub.com.


[8]ページ先頭

©2009-2025 Movatter.jp