-
Notifications
You must be signed in to change notification settings - Fork 3
/
plugin.js
53 lines (46 loc) · 1.62 KB
/
plugin.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
const { Compilation } = require('webpack');
const mjml2html = require('mjml');
const fs = require('fs');
class MjmlPlugin {
/**
* Create a new MJML plugin instance.
*
* @param {Array} toCompile
*/
constructor(toCompile) {
this.toCompile = toCompile;
}
/**
* Apply the plugin.
*
* @param {Object} compiler
*/
apply(compiler) {
compiler.hooks.compilation.tap('MjmlPlugin', (compilation) => {
compilation.hooks.processAssets.tap({
name: 'MjmlPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
}, () => {
this.toCompile.forEach(({ entry, output, mjmlOptions }) => {
compilation.fileDependencies.add(entry);
let response;
try {
response = mjml2html(fs.readFileSync(entry, 'utf8'), mjmlOptions);
} catch (e) {
response = { errors: [{ formattedMessage: e.toString() }] };
}
if (response.errors.length) {
const errors = response.errors.map(err => err.formattedMessage).join('\n- ');
compilation.errors.push(`MJML compilation failed for "${entry}"\n- ${errors}`);
return;
}
compilation.emitAsset(output, {
source: () => response.html,
size: () => response.html.length
});
});
});
});
}
}
module.exports = MjmlPlugin;