I would like to make use of a function called executeJavaScript() from the Electron webContents API. Since it is very close to eval() I will use this in the example.
The problem:
- I have a decent sized script but it is contained in a template string.
- Expanding this app, the script could grow a lot as a string.
- I am not sure what the best practices are for this.
I also understand that eval()
is dangerous, but I am interested in the principal of my question.
Basic eval example for my question:
// Modules
const fs = require('fs');
// CONSTANTS
const EXAMPLE_1 = 'EXAMPLE_1';
const EXAMPLE_2 = 'EXAMPLE_2';
const EXAMPLE_3 = 'EXAMPLE_3';
const exampleScriptFunction = require('./exampleScriptFunction');
const exampleScriptFile = fs.readFileSync('./exampleScriptFile.js');
// using direct template string
eval(`console.log(${EXAMPLE_1})`);
// using a method from but this doesnt solve the neatness issue.
eval(exampleScriptFunction(EXAMPLE_2));
// What I want is to just use a JS file because it is neater.
eval(`${exampleScriptFile}`);
exampleScriptFunction.js
module.exports = function(fetchType) {
return `console.log(${fetchType});`;
}
- This will allow me to separate the script to a new file
- what if I have many more then 1 variable???
exampleScriptFile.js:
console.log(${EXAMPLE_3});
- This clearly does not work, but I am just trying to show my thinking.
- back ticks are not present, fs loads as string, main file has back ticks.
- This does not work. I do not know how else to show what I mean.
- Because I am loading this will readFileSync, I figured the es6 template string would work.
- This allows me to write a plain js file with proper syntax highlighting
- The issue is the variables are on the page running the eval().
Perhaps I am completely wrong here and looking at this the wrong way. I am open to suggestions. Please do not mark me minus 1 because of my infancy in programming. I really do not know how else to ask this question. Thank you.