Convert Figma logo to code with AI

actions logotypescript-action

Create a TypeScript Action with tests, linting, workflow, publishing, and versioning

1,968
463
1,968
4

Top Related Projects

100,112

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

5,905

:vertical_traffic_light: An extensible linter for the TypeScript language

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

12,836

TypeScript execution and REPL for node.js

The repository for high quality TypeScript type definitions.

Quick Overview

The actions/typescript-action repository is a template for creating TypeScript-based GitHub Actions. It provides a starting point for developers who want to create their own custom GitHub Actions using TypeScript.

Pros

  • Typescript Support: The template is designed specifically for TypeScript, which provides better type safety and tooling compared to plain JavaScript.
  • Automated Workflow: The repository includes a pre-configured GitHub Actions workflow that automatically builds, tests, and publishes the action.
  • Dependency Management: The project uses npm for dependency management, making it easy to add and update dependencies as needed.
  • Comprehensive Documentation: The repository includes detailed documentation on how to use the template and create a new GitHub Action.

Cons

  • Limited Functionality: The template is a starting point and does not include any specific functionality beyond the basic structure of a GitHub Action.
  • Dependency on GitHub Actions: The template is designed specifically for creating GitHub Actions, which means it may not be suitable for other types of projects.
  • Potential Complexity: While the template simplifies the process of creating a GitHub Action, there may still be a learning curve for developers who are new to GitHub Actions or TypeScript.
  • Maintenance Overhead: As with any project, maintaining and updating the template may require ongoing effort from the maintainers.

Code Examples

Here are a few examples of how you might use the actions/typescript-action template to create a custom GitHub Action:

  1. Greeting Action:
import * as core from '@actions/core';

async function run(): Promise<void> {
  try {
    const name = core.getInput('name');
    core.setOutput('greeting', `Hello, ${name}!`);
  } catch (error) {
    core.setFailed(error.message);
  }
}

run();

This example demonstrates how to use the @actions/core library to get input from the action's configuration, and set an output value that can be used by other steps in the workflow.

  1. File Linting Action:
import * as core from '@actions/core';
import * as github from '@actions/github';
import * as fs from 'fs';

async function run(): Promise<void> {
  try {
    const filePath = core.getInput('file-path');
    const content = fs.readFileSync(filePath, 'utf8');

    // Perform linting logic here
    const hasErrors = checkForErrors(content);

    core.setOutput('has-errors', hasErrors);
  } catch (error) {
    core.setFailed(error.message);
  }
}

function checkForErrors(content: string): boolean {
  // Implement linting logic here
  return content.includes('error');
}

run();

This example shows how to use the @actions/core and @actions/github libraries to read a file, perform some linting logic, and set an output value based on the result.

  1. Deployment Action:
import * as core from '@actions/core';
import * as exec from '@actions/exec';

async function run(): Promise<void> {
  try {
    const environment = core.getInput('environment');
    const command = core.getInput('command');

    await exec.exec(command, [], {
      env: {
        ENVIRONMENT: environment
      }
    });

    core.setOutput('deployment-status', 'success');
  } catch (error) {
    core.setFailed(error.message);
  }
}

run();

This example demonstrates how to use the @actions/exec library to execute a command, passing in environment variables as needed, and set an output value based on the result of the deployment.

Getting Started

To get started with the actions/typescript-action template, follow these steps:

  1. Fork the repository to your own GitHub account.
  2. Clone the forked repository to your local machine.
  3. Install the project dependencies by running npm install.
  4. Modify the action.yml file to define the inputs, outputs, and other metadata for your custom GitHub Action.
  5. Implement the logic for your action in the src/main.ts file.
  6. Add any necessary tests in the

Competitor Comparisons

100,112

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

Pros of TypeScript

  • Comprehensive language implementation with full TypeScript compiler
  • Extensive documentation and community support
  • Regular updates and maintenance from Microsoft

Cons of TypeScript

  • Larger repository size and complexity
  • Not specifically designed for GitHub Actions
  • Steeper learning curve for beginners

Code Comparison

TypeScript:

interface Person {
  name: string;
  age: number;
}

function greet(person: Person) {
  return `Hello, ${person.name}!`;
}

typescript-action:

import * as core from '@actions/core';

try {
  const name: string = core.getInput('name');
  console.log(`Hello ${name}!`);
} catch (error) {
  core.setFailed(error.message);
}

Key Differences

  • TypeScript focuses on language implementation, while typescript-action is tailored for GitHub Actions
  • typescript-action includes GitHub Actions-specific libraries and utilities
  • TypeScript provides a more general-purpose development environment

Use Cases

  • Choose TypeScript for general TypeScript development and larger projects
  • Opt for typescript-action when creating GitHub Actions with TypeScript

Community and Support

  • TypeScript has a larger community and more extensive third-party resources
  • typescript-action benefits from GitHub's official support and integration with Actions
5,905

:vertical_traffic_light: An extensible linter for the TypeScript language

Pros of TSLint

  • More comprehensive linting rules and configuration options
  • Longer development history and larger community support
  • Extensive documentation and examples available

Cons of TSLint

  • Deprecated in favor of ESLint, with limited future updates
  • Potentially slower performance for large codebases
  • Steeper learning curve due to more complex configuration

Code Comparison

TSLint configuration example:

{
  "rules": {
    "no-unused-variable": true,
    "no-console": [true, "log", "error"],
    "quotemark": [true, "single"]
  }
}

TypeScript Action workflow example:

name: 'Hello World'
on:
  push:
    branches: [ main ]
jobs:
  hello_world_job:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/hello-world-typescript-action@v1
        with:
          who-to-greet: 'Mona the Octocat'

Summary

While TSLint offers more comprehensive linting capabilities and has a longer history, it's important to note that it's been deprecated in favor of ESLint. TypeScript Action, on the other hand, focuses on creating GitHub Actions using TypeScript, providing a streamlined approach for workflow automation. The choice between the two depends on the specific needs of your project, whether it's code quality enforcement or GitHub Actions development.

:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

Pros of typescript-book

  • Comprehensive learning resource for TypeScript
  • Regularly updated with new TypeScript features and best practices
  • Community-driven with contributions from various developers

Cons of typescript-book

  • Not directly related to GitHub Actions development
  • May contain more theoretical content than practical examples
  • Requires more time investment to extract actionable insights

Code Comparison

typescript-book (example of TypeScript basics):

let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let x: [string, number] = ["hello", 10];

typescript-action (example of GitHub Action setup):

import * as core from '@actions/core';
import * as github from '@actions/github';

async function run() {
  try {
    const myInput = core.getInput('myInput');
    core.setOutput('myOutput', `Hello ${myInput}`);
  } catch (error) {
    core.setFailed(error.message);
  }
}

run();

The typescript-book repository focuses on teaching TypeScript concepts, while typescript-action provides a template for creating GitHub Actions using TypeScript. The code examples reflect this difference, with typescript-book showing basic TypeScript syntax and typescript-action demonstrating integration with GitHub Actions API.

12,836

TypeScript execution and REPL for node.js

Pros of ts-node

  • Broader application: Can be used for general TypeScript execution, not limited to GitHub Actions
  • REPL support: Provides an interactive TypeScript REPL for quick testing and experimentation
  • Extensive configuration options: Offers more flexibility in how TypeScript is compiled and executed

Cons of ts-node

  • Not tailored for GitHub Actions: Lacks specific features for creating and packaging GitHub Actions
  • Larger dependency footprint: Includes more dependencies, which may increase project size
  • Potential performance overhead: May have slightly slower startup times due to on-the-fly compilation

Code Comparison

ts-node usage:

import * as ts from "typescript";
import { createContext, runInContext } from "vm";

const context = createContext({});
const result = runInContext("const x: number = 5; x * 2", context);
console.log(result); // Output: 10

typescript-action usage:

import * as core from '@actions/core';
import * as github from '@actions/github';

try {
  const nameToGreet = core.getInput('who-to-greet');
  console.log(`Hello ${nameToGreet}!`);
} catch (error) {
  core.setFailed(error.message);
}

The repository for high quality TypeScript type definitions.

Pros of DefinitelyTyped

  • Extensive collection of TypeScript type definitions for numerous libraries
  • Community-driven project with a large number of contributors
  • Regularly updated and maintained for a wide range of packages

Cons of DefinitelyTyped

  • Not specifically designed for GitHub Actions
  • May include unnecessary type definitions for action development
  • Requires manual selection of relevant type definitions

Code Comparison

DefinitelyTyped:

// Example from @types/node
declare module "fs" {
    export function readFile(path: string, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void;
    // ...
}

typescript-action:

import * as core from '@actions/core'
import * as github from '@actions/github'

async function run(): Promise<void> {
  try {
    const ms: string = core.getInput('milliseconds')
    // ...
  } catch (error) {
    core.setFailed(error.message)
  }
}

The typescript-action repository provides a streamlined template specifically for creating GitHub Actions using TypeScript. It includes the necessary dependencies and structure for action development. On the other hand, DefinitelyTyped offers a comprehensive collection of type definitions for various JavaScript libraries, which can be beneficial for larger projects or when working with multiple external dependencies in your action.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Create a GitHub Action Using TypeScript

GitHub Super-Linter CI Check dist/ CodeQL Coverage

Use this template to bootstrap the creation of a TypeScript action. :rocket:

This template includes compilation support, tests, a validation workflow, publishing, and versioning guidance.

If you are new, there's also a simpler introduction in the Hello world JavaScript action repository.

Create Your Own Action

To create your own action, you can use this repository as a template! Just follow the below instructions:

  1. Click the Use this template button at the top of the repository
  2. Select Create a new repository
  3. Select an owner and name for your new repository
  4. Click Create repository
  5. Clone your new repository

[!IMPORTANT]

Make sure to remove or update the CODEOWNERS file! For details on how to use this file, see About code owners.

Initial Setup

After you've cloned the repository to your local machine or codespace, you'll need to perform some initial setup steps before you can develop your action.

[!NOTE]

You'll need to have a reasonably modern version of Node.js handy (20.x or later should work!). If you are using a version manager like nodenv or nvm, this template has a .node-version file at the root of the repository that will be used to automatically switch to the correct version when you cd into the repository. Additionally, this .node-version file is used by GitHub Actions in any actions/setup-node actions.

  1. :hammer_and_wrench: Install the dependencies

    npm install
    
  2. :building_construction: Package the TypeScript for distribution

    npm run bundle
    
  3. :white_check_mark: Run the tests

    $ npm test
    
    PASS  ./index.test.js
      ✓ throws invalid number (3ms)
      ✓ wait 500 ms (504ms)
      ✓ test runs (95ms)
    
    ...
    

Update the Action Metadata

The action.yml file defines metadata about your action, such as input(s) and output(s). For details about this file, see Metadata syntax for GitHub Actions.

When you copy this repository, update action.yml with the name, description, inputs, and outputs for your action.

Update the Action Code

The src/ directory is the heart of your action! This contains the source code that will be run when your action is invoked. You can replace the contents of this directory with your own code.

There are a few things to keep in mind when writing your action code:

  • Most GitHub Actions toolkit and CI/CD operations are processed asynchronously. In main.ts, you will see that the action is run in an async function.

    import * as core from '@actions/core'
    //...
    
    async function run() {
      try {
        //...
      } catch (error) {
        core.setFailed(error.message)
      }
    }
    

    For more information about the GitHub Actions toolkit, see the documentation.

So, what are you waiting for? Go ahead and start customizing your action!

  1. Create a new branch

    git checkout -b releases/v1
    
  2. Replace the contents of src/ with your action code

  3. Add tests to __tests__/ for your source code

  4. Format, test, and build the action

    npm run all
    

    This step is important! It will run ncc to build the final JavaScript action code with all dependencies included. If you do not run this step, your action will not work correctly when it is used in a workflow. This step also includes the --license option for ncc, which will create a license file for all of the production node modules used in your project.

  5. Commit your changes

    git add .
    git commit -m "My first action is ready!"
    
  6. Push them to your repository

    git push -u origin releases/v1
    
  7. Create a pull request and get feedback on your action

  8. Merge the pull request into the main branch

Your action is now published! :rocket:

For information about versioning your action, see Versioning in the GitHub Actions toolkit.

Validate the Action

You can now validate the action by referencing it in a workflow file. For example, ci.yml demonstrates how to reference an action in the same repository.

steps:
  - name: Checkout
    id: checkout
    uses: actions/checkout@v4

  - name: Test Local Action
    id: test-action
    uses: ./
    with:
      milliseconds: 1000

  - name: Print Output
    id: output
    run: echo "${{ steps.test-action.outputs.time }}"

For example workflow runs, check out the Actions tab! :rocket:

Usage

After testing, you can create version tag(s) that developers can use to reference different stable versions of your action. For more information, see Versioning in the GitHub Actions toolkit.

To include the action in a workflow in another repository, you can use the uses syntax with the @ symbol to reference a specific branch, tag, or commit hash.

steps:
  - name: Checkout
    id: checkout
    uses: actions/checkout@v4

  - name: Test Local Action
    id: test-action
    uses: actions/typescript-action@v1 # Commit with the `v1` tag
    with:
      milliseconds: 1000

  - name: Print Output
    id: output
    run: echo "${{ steps.test-action.outputs.time }}"

Publishing a New Release

This project includes a helper script, script/release designed to streamline the process of tagging and pushing new releases for GitHub Actions.

GitHub Actions allows users to select a specific version of the action to use, based on release tags. This script simplifies this process by performing the following steps:

  1. Retrieving the latest release tag: The script starts by fetching the most recent SemVer release tag of the current branch, by looking at the local data available in your repository.
  2. Prompting for a new release tag: The user is then prompted to enter a new release tag. To assist with this, the script displays the tag retrieved in the previous step, and validates the format of the inputted tag (vX.X.X). The user is also reminded to update the version field in package.json.
  3. Tagging the new release: The script then tags a new release and syncs the separate major tag (e.g. v1, v2) with the new release tag (e.g. v1.0.0, v2.1.2). When the user is creating a new major release, the script auto-detects this and creates a releases/v# branch for the previous major version.
  4. Pushing changes to remote: Finally, the script pushes the necessary commits, tags and branches to the remote repository. From here, you will need to create a new release in GitHub so users can easily reference the new tags in their workflows.