Writing npm scripts using TypeScript
In my TypeScript projects I have been using npm scripts for the development and build pipelines.
As a side note — if you are using gulp or grunt, you should check out this blog post about the reasons why to move to npm scripts.
Typically my scripts have been defined in my package.json and simply call CLI tools. Recently I was working with json-server and json-schema-faker (view this blog post to find out more) and I needed to do more than what would fit elegantly into a single line in package.json. I could have used a JavaScript file, since I don’t really need the full power of TypeScript for a build script. However I wanted to be consistent across my project and have the same rules/checks performed on all my code.
To use TypeScript to define your build scripts, you can use the ts-node module. ts-node is a TypeScript execution environment and REPL for node, meaning you can use a TypeScript file in place of any JavaScript file.
First of all, install ts-node and typescript (which ts-node depends on) with:
yarn install -D ts-node typescript
Now with the modules installed, you can create a npm script like the following:
"start" : "ts-node ./buildScripts/start.ts"
And run it with:
yarn start
That’s it! An example project with all this setup can be found on my GitHub.
One thing I did come across is that your tsconfig.json needs to have module format set to “commonjs” for ts-node to work correctly; otherwise you will get the error “SyntaxError: Unexpected token import”. If you want to use a different module format in the rest of your code, you could use a separate tsconfig.json for the build scripts, this is demonstrated in my example project.