UNPKG

1.54 kBJavaScriptView Raw
1const { template } = require('lodash');
2const { promisify } = require('util');
3const fs = require('fs');
4
5/**
6 * Light wrapper over lodash templates making it safer to be used with javascript source code.
7 *
8 * In particular, doesn't interfere with use of interpolated strings in javascript.
9 *
10 * @param {string} content Template source
11 * @param {_.TemplateOptions} options Template options
12 */
13const jsSourceTemplate = (content, options) =>
14 template(content, {
15 interpolate: /<%=([\s\S]+?)%>/g,
16 ...options,
17 });
18
19const readFile = promisify(fs.readFile, { context: fs });
20const writeFile = promisify(fs.writeFile, { context: fs });
21
22/**
23 * Compile the contents of specified (javascript) file as a lodash template
24 *
25 * @param {string} filePath Path of file to be used as template
26 * @param {_.TemplateOptions} options Lodash template options
27 */
28const jsFileTemplate = async (filePath, options) => {
29 const contentBuffer = await readFile(filePath);
30 return jsSourceTemplate(contentBuffer.toString(), options);
31};
32
33/**
34 * Write a javascript file using another file as a (lodash) template
35 *
36 * @param {string} targetFilePath
37 * @param {string} sourceFilePath
38 * @param {_.TemplateOptions} options options passed to lodash templates
39 */
40const writeJsFileUsingTemplate = async (
41 targetFilePath,
42 sourceFilePath,
43 options,
44 variables
45) =>
46 writeFile(
47 targetFilePath,
48 (await jsFileTemplate(sourceFilePath, options))(variables)
49 );
50
51module.exports = {
52 jsSourceTemplate,
53 jsFileTemplate,
54 writeJsFileUsingTemplate,
55};