'Running into reference error with lodash.template

Edit

I ended up replacing all '$' in the file with '$' and doing the following:

await fsPromises.writeFile(
    targetFilePath,
    compiledSourceFile({
        schemaName: schema.schema_name
    }).replace('$', '$', 'ig')
);

I have a simple file with the following contents:

const { executeQuery } = require('../../db');

const getAllTableRecords = async ({ tableName }) =>
    executeQuery({
        query: `
            SELECT
                *,
                '${tableName}' as "table_name"
            FROM <%= schemaName %>.${tableName}
        `,
    });

module.exports = {
    getAllTableRecords,
};

I try to programmatically read this file and output it to a different directory:

import path from 'path';
import { promises as fsPromises } from 'fs';
import { template } from 'lodash';

const sourceFilePath = path.join(__dirname, 'utils', 'index.js');
const compiledSourceFile = template(sourceFile);
const targetFilePath = path.resolve(__dirname, 'temp', 'utils', 'index.js');

const [sourceFile] = await Promise.all([
    fsPromises.readFile(sourceFilePath, 'utf-8'),
    fsPromises.mkdir(targetFilePath, { recursive: true })
]);

await fsPromises.writeFile(targetFilePath, compiledSourceFile({ schemaName: schema.schema_name }));

All this does is read the template file, replace the values in the template and recursively create and write to the target destination.

But this throw an error,

ReferenceError: tableName is not defined

It seems as though lodash.template can't process the template literal ${}. It keeps failing at this line,

SELECT
    *,
    '${tableName}' as "table_name"
    ^^^^^^^^^^^^^^

What are my options here if I want to stick to template literals?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source