Running script when ts-node-dev restarts server

Viewed 8630

I currently have ts-node-dev installed with my node js server and have it watching my .ts files with the --respawn flag. My server is getting successfully restarted, but I when a .ts file changes, I need to run a command like yarn build to compile the changed files (or all files) to make sure my changes are present in the restarted server.

I can't seem to find a way to run a script when the server restarts.

I have tried something like:

"start": "ts-node-dev --respawn --transpile-only yarn build && src/main.js"

In my package.json, but it tries to resolve my yarn build command as a file name.

How can I tie a script into my restarting process?

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es2017",
    "lib": ["es2017", "esnext.asynciterable"],
    "module": "commonjs",
    "moduleResolution": "node",

    "rootDir": ".",
    "sourceMap": true,
    "newLine": "LF",

    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "strict": true,

    // For typeORM support
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strictPropertyInitialization": false,

    "pretty": true,
    "typeRoots": ["node_modules/@types"]
  },
  "include": ["src/**/*", "db/**/*", "swagger/**/*", "test/**/*"]
}

This is my tsconfig.json, how do I specify with the watch command to watch all the src files and folders?

1 Answers

According ts-node-dev documentation the command is:

ts-node-dev --respawn --transpileOnly <YOUR TS FILE>

You should try on your start script on package.json:

"dev": "ts-node-dev --respawn --transpileOnly --watch src,db,swagger,test src/main.ts"
"start": "node dist/src/main.js"

In your tsconfig.json file, you should have the outDir config, this config defines the folder that you compiled code will be placed, for instance, look at my tsconfig.json:

{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "ES2017",
        "moduleResolution": "node",
        "outDir": "./dist",
        "strict": true,
        "strictPropertyInitialization": false,
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    },
    "exclude": ["node_modules"],
    "include": [
        "./src/**/*.tsx",
        "./src/**/*.ts",
        "src/__tests__",
        "./src/**/*",
    ]  
}

I have the outDir config, when I run tsc or npm run build, a dist folder will be created, and inside there's will be all my .js files

Related