Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch template files and copy them to dist/ folder

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?
like image 340
Jaime Sangcap Avatar asked Nov 07 '17 13:11

Jaime Sangcap


2 Answers

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"
  }
}
like image 145
0zkr PM Avatar answered Oct 19 '22 05:10

0zkr PM


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"
  }
}
like image 25
Anna Medyukh Avatar answered Oct 19 '22 07:10

Anna Medyukh