5
votes

I'm using typescript on my project and I can successfully watch + compile .ts files and output them to dist folder.

here is the scripts part of my package.json

"start": "npm run build && npm run watch",
    "build": "npm run build-ts && npm run tslint",
    "test": "cross-env NODE_ENV=test jest --watch",
    "watch": "concurrently -k -p \"[{name}]\" -n \"Typescript,Node\" -c \"cyan.bold,green.bold\" \"npm run watch-ts\" \"npm run serve\"",
    "serve": "nodemon dist/server.js",
    "build-ts": "tsc",
    "watch-ts": "tsc -w",
    "tslint": "tslint -c tslint.json -p tsconfig.json"

The problem is I want to use js templating engine (nunjucks) and I need to watch the view files inside the views folder and move them to the dist folder.

  • Is there a way by just using npm scripts or nodejs?
  • Or do I need to use other tools like gulp or webpack?
3

3 Answers

4
votes

I have the "same" request to for a CRUD graphql back-end server, but don't want to use gulp or webpack just to keep it simple.

I see that you use nodemon like me. Then, according the docs at https://github.com/remy/nodemon, it can be used it to monitor changes of any kind of file other than the default js. More over, nodemon can monitor the status of other transactional server other than node.

The first task is detecting the changes of wanted files: in my case I want copy the *.gql files in my src/schema folder to build/schema folder. For that, you can use the ext for the kind of files, and watch option for the source folder to explore.

The second one task is matter of copying the files. Naturally, you can use the copy command of your host OS. In my case I use the DOS xcopy command of the Windows shell (or cp in Unix like OS). nodemon has an "event-hook" with the event option, that can execute a command line when an event occurs. Just we need the restart event of the node server when the changes are detected for nodemon.

You can use the command line options, or a global config file, or in you local package.json project config file. I show up the last one using nodemonConfig section of package.json:

"nodemonConfig": {
  "watch": [
     "./src/schema",
     "./build"
  ],
  "ext": "js,gql",
  "events": {
     "restart": "xcopy .\\src\\schema\\*.gql .\\build\\schema /Y /O /R /F /I /V /E"
  }
}
2
votes

Ozkr's answer is great, I just want to add what worked for me, I had to change it a bit as nodemon was running into an infinite restart otherwise:

"nodemonConfig": {
"watch": [
   "./views",
   "./public"
],
"ext": "hjs,js",
"events": {
   "restart": "cp -r views dist \n cp -r public dist"
  }
}
0
votes

copy-and-watch does just that:

I use this code to copy html files during development:

"copy_html": "yarn copy-and-watch src/mail_templates/* prod/mail_templates --watch --clean",