-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.js
64 lines (49 loc) · 1.57 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const fs = require('fs');
const path = require('path');
const mjml2html = require('mjml').mjml2html;
const builder = {};
function getTemplateFilename(filePath) {
const split = filePath.split('/');
return split[split.length - 1];
}
function mkdir(directory) {
try {
fs.readdirSync(directory);
} catch (err) {
fs.mkdirSync(directory);
}
}
builder.build = (filePath, outputDir, extension) => {
// No-op if filePath is not a file
if (!fs.statSync(filePath).isFile()) {
return;
}
const filename = getTemplateFilename(filePath).replace('.mjml', extension);
try {
const outputPath = path.join(process.cwd(), outputDir);
mkdir(outputPath);
const startTime = Date.now();
const data = fs.readFileSync(`${filePath}`, 'utf8');
const rendered = mjml2html(data);
fs.writeFileSync(`${outputPath}/${filename}`, rendered.html);
const endTime = Date.now();
const totalTime = endTime - startTime;
console.log(`Rendered ${filename} in ${totalTime}ms`); // eslint-disable-line
} catch (error) {
console.error(`Unable to render ${filename}`);
console.error(error.message);
}
};
builder.buildAll = (inputDir, outputDir, extension) => {
const sourcePath = path.join(process.cwd(), inputDir);
const templates = fs.readdirSync(sourcePath);
if (!templates.length) {
throw new Error('No templates to build');
}
const outputPath = path.join(process.cwd(), outputDir);
mkdir(outputPath);
templates.forEach((template) => {
builder.build(`${sourcePath}/${template}`, outputDir, extension);
});
};
module.exports = builder;