Sub topic 2
Using `@actions/core` and `@actions/github`
Assume you know workflow syntax, JavaScript and npm, basic Docker, Git, and a shell. This chapter connects an action's JavaScript code to its metadata and workflow.
Use the Actions toolkit
@actions/core is the toolkit package for inputs, outputs, logs, and failures. @actions/github exposes GitHub context, such as the event name and commit SHA.
const core = require("@actions/core");
const github = require("@actions/github");
try {
const name = core.getInput("who-to-greet", { required: true });
core.info(`Hello ${name}!`);
core.setOutput("time", new Date().toISOString());
core.info(`Event: ${github.context.eventName}`);
} catch (error) {
core.setFailed(error instanceof Error ? error.message : String(error));
}The try block handles normal work. setFailed marks the step as failed and gives the user a readable message.
Bundle dependencies
GitHub-hosted runners do not install your action's npm dependencies automatically. Install them, then bundle the action and commit the generated file.
npm install @actions/core @actions/github
npm install --save-dev @vercel/ncc
npx ncc build index.js --minify --out distSet runs.main to the bundled file:
runs:
using: node20
main: dist/index.jsCommit dist/index.js with the source. A consumer should be able to use a tagged action without running npm.
Set outputs with workflow commands
core.setOutput writes an output through GitHub's environment-file protocol. A shell action uses the same protocol directly:
echo "time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"The workflow reads that value through the step ID:
- id: greet
uses: ./
with:
who-to-greet: Mona
- run: echo "${{ steps.greet.outputs.time }}"Build a Docker action
A Docker action uses a Dockerfile instead of Node on the runner. Its entrypoint receives declared arguments and writes outputs to GITHUB_OUTPUT.
FROM alpine:3.20
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]#!/bin/sh -l
set -eu
echo "Hello $1"
printf 'time=%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"JavaScript actions usually start faster and work on more runner types. Docker actions provide a controlled Linux environment but require Docker and add startup time.
Exercise
Why must a JavaScript action commit its bundled dist/index.js file?
Show answer
The runner executes the action directly and does not install its npm dependencies for the action.