Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a javascript file with nodeJs

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?

like image 318
Jeanluca Scaljeri Avatar asked Jan 28 '23 02:01

Jeanluca Scaljeri


2 Answers

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.

like image 164
mihai Avatar answered Jan 29 '23 16:01

mihai


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

like image 36
Arthur Eudeline Avatar answered Jan 29 '23 15:01

Arthur Eudeline