My site requires a JSON which I can generate during the build process.
So, what I would like to do is generate a js-file with, for example, the following content:
export const PREFIX = 'foo';
export const IMPORT_STUFF = {
a: 10,
....
}
The easiest way, for me, would be something like this:
const TEMPLATE = `export PREFIX = '--foo--';
export const IMPORT_STUFF = `;
let output = TEMPLATE.replace('--foo--', myPefix);
output += JSON.stringify(importObj);
createJsFile(output);
When things get more complex I can imagine that this approach is not ideal, so I was wondering if there are better ways to do something like this?
You can use ejs to render some basic templates. It's a templating engine usually used to render javascript inside html, but in this case you'll be rendering javascript inside a string.
const ejs = require('ejs');
var myPrefix = 'foo';
var importObj = {a: 10}
const TEMPLATE = `export PREFIX = '<%= Prefix %>';
export const IMPORT_STUFF = <%- JSON.stringify(ImportObj) %>`;
let output = ejs.render(TEMPLATE, {Prefix: myPrefix, ImportObj: importObj});
The code enclosed in <%= %>
or <%- %>
will be executed as javascript, using the object you provide as the second argument to ejs.render
.
The syntax <%- %>
is used when you don't want to html encode the output.
If ejs is too much for you you can always go back to plain string interpolation (provided by template literals):
var myPrefix = 'foo';
var importObj = {a: 10}
importObj = JSON.stringify(importObj)
var output = `export PREFIX = '${myPrefix}';
export const IMPORT_STUFF = ${importObj}`
However this doesn't allow you to read the template from an external file for example, so I would go for ejs which is the better option in this scenario.
You can also use the native method util.inspect
to write plain JavaScript objects in a file like this :
// ...
// If we wants to adds the 'module.exports = ' part before
fs.writeFileSync( process.cwd() + '/file.js', 'module.exports = ');
// Writes the plain object to the file
fs.appendFileSync( process.cwd() + '/file.js', util.inspect(options));
I have more detailed my solution in this answer if anyone needs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With