Writing a short fish function to create a boilerplate typescript setup

Posted on:October 20, 2023

Here I show my function to quickly setup new node.js projects in typescript. This function removes the need to memorize all these commands, and is great for quickly getting a demo typescript project whipped up.

Table of contents

Open Table of contents

Precursor

Before seeing/using this function, it is important that both your npm and npx are setup correctly. Privelege errors in relation to these commands are indicitive of these commands not properly being setup.

If you are certain that these commands are working, I also highly recommend the following packages to be globally installed on your machine:

The function

Here I have named the function tsc_starter and placed it in the following location: ~/.config/fish/funcitons/tsc_starter.fish

function tsc_starter
    set_color red
    echo (dirname $PWD)
    read -n 1 -P 'run starter script here? [Y/n]' -l continue
    switch $continue
        case 'n' 'N' ''
            return 1
        case 'y' 'Y'
            __tsc_starter_helper
            return 0
        case '*'
            return 1
    end
end

function __tsc_starter_helper
    npm init -y
    npm i typescript --save-dev
    npm install @types/node --save-dev
    npx tsc --init --rootDir src --outDir out --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
    mkdir -p {src,out}
    echo 'console.log("hello world!")' > src/index.ts
    printf '\n%s\n' 'CREATED';exa -I 'node_modules' -T --color always; echo "";
    nodemon src/index.ts
end

Note: I also use the command exa to display the projects file tree.

Wrapping Up

Now we can use the tsc_starter command in a directory we want to setup a typscript project. I use this function in the following manor:

  1. cd some_typescript_template_directory/
  2. tsc_starter