Recently I received a request to send daily mail in HTML format during the promotion period. However, in the development process, the back-end uses VM template, and does not provide the corresponding environment to view THE HTML results, can only generate HTML through Java, in Outlook to see the effect. This results in resending the email every time you try to change the style, and no debugging is possible. To do this, you need to compile the VM directly in JavaScript to generate HTML that can be seen in the browser

NPM packages involved

  • watchpack: used to monitor file changes and implement whenvmAutomatically compile when a file changes.webpackthewatchFunctionality is implemented through this package
  • velocityjs:JavaScriptVersion of thevmCompile engine, which will be used to implementvmCompiled intohtml

The source code

const path = require("path");
const fs = require('fs');
const Watchpack = require("watchpack");
const velocity = require('velocityjs');

const wp = new Watchpack({
    aggregateTimeout: 100.poll: true.followSymlinks: true.ignored: "**/.git"
});

wp.watch({
    files: [
        path.join(__dirname, 'day.vm'),
        path.join(__dirname, 'hour.vm')].startTime: Date.now() - 10000
});

wp.on("change".function (filePath, mtime, explanation) {
    console.log(filePath, 'File changes')
    let context = {};
    if (filePath.indexOf('day')! = = -1) {
        context = {
            dt: ["11/01"."11/02".'11/03'.'11/04']}; }else if (filePath.indexOf('hour')! = = -1) {
        context = {
            weekStr: 'on Wednesday'
        };
    }
    fs.writeFileSync(
        filePath.replace('vm'.'html'),
        velocity.render(fs.readFileSync(filePath, 'utf-8'), context)
    )
});
Copy the code