Published on

Running a Single TypeScript file from your project

Authors

From time to time you may want to be able to run a single TypeScript file from your project. For example in my case I had a migration script I wanted to be able to run from an npm script.

My project structure looked as follows:

package.json
...
yarn.lock
ts/
   ->
     src/
         ...
          ->
             scripts/
                      -> data/
                               -> myData.ts
                      -> migrate.ts

I already had a build script in my package.json that handled the ts build:

"build:ts": "tsc -p ts/tsconfig.json",

Adding a migrate:local package.json script was actually fairly straightforward (much more so than if this were JavaScript with babel).

The basic principles for this script were:

  • Rely on the tsconfig.json file to worry about your ts configuration.
  • First run the build script build:ts which outputs the js version of your ts files.
  • Use node to run the generated migrate.js file or whatever other file/s you want.

With this in mind I simply added the below script to my package.json file:

"migrate:local": "yarn build:ts && node ts/lib/scripts/migrate.js"

In the above my ts compiler is configured to put the built js files into ts/lib.

My migrate.js uses a self executing function to allow me to run async items:

import * as _ from 'lodash';
...
import { data } from './data/myData';

(async () => {
    //do whatever you need to do here
    // you can use await as this enclosing function is async
})().catch(console.log);

The beauty with using this approach is that you have full access to all your project's dependencies and you do not have to do anything fancy to be able to access them - you rely on the TypeScript compiler (tsc) to generate your js script file and simply use node to run the file.