Search code examples
javascriptnode.jselectronejselectron-builder

EJS not rendering after using electron builder


I am trying to render an ejs file in my electron.js app. I am loading the ejs file using the following skeleton:

const ejs = require('ejs')

ejs.renderFile('views/list.ejs', { data: listData }, { root: __dirname }, function (err, str) {
        if (err) {
            console.log(err);
        }
        mainWindow.loadURL('data:text/html;charset=utf-8,' + encodeURI(str));
});

Now this is working properly in the dev environment(i.e. using electron . command), but when I build the app using electron-builder, and run the app, the ejs does not render and is just a blank page with undefined printed.

Any ideas why this is happening and how to fix it?


Solution

  • for posterity: I FIGURED IT OUT (ish)

    For some reason, ejs.renderFile() needs an absolute path when the app is built with electron-builder.

    So, you need to do like this: ${path.join(__dirname, ./${consequence}.ejs)}

    ejs.renderFile(`${path.join(__dirname, `views/list.ejs`)}`, { data: listData }, { root: __dirname }, 
        function (err, str) {
            if (err) {
                console.log(err);
            }
            mainWindow.loadURL('data:text/html;charset=utf-8,' + encodeURI(str));
        }
    );
    

    As to WHY this is the case, I do not know (since __dirname is included as "root" option param...I'm guessing there is a bug.