简体   繁体   中英

How do I auto generate .ts files in VSCode?

I have a.json file that changes quite often and I would like to auto generate a.ts file every time the.json file is saved.

I want to write the logic of the converter from the.json to.ts myself. How is this achieved with VSCode?

Depending on your use case, this may not be the best approach, but there is a plugin called Run on Save that executes a command when you save a file. If you have a script in ts/js that converts the.json to.ts, you can execute it with the nodejs runtime.

A sample config could look like:

"emeraldwalk.runonsave": {
    "commands": [
        {
            "match": "file.json$",
            "cmd": "ts-node export.ts ${file}"
        },
    ]
}

Your export.ts script would be running in the nodejs runtime, so you'll have access to the fs module . This gives you the ability to read and write files to the disk. A sample could look like:

var fs = require('fs');

fs.readFile(process.argv[2], function (err, data) {
  if (err) throw err;
  
  //conversion would be here
  let jsonPayload = data;

  fs.appendFile('newTsFile.ts', jsonPayload, function (err) {
    if (err) throw err;
    console.log('Updated!');
  }); 
}); 


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM