jsoverson / preprocess

Preprocess HTML, JavaScript, and other files with directives based off custom or ENV configuration
Other
366 stars 80 forks source link

Allow objects to be passed to `@echo` directive #48

Open gevgeny opened 9 years ago

gevgeny commented 9 years ago

Currently passing an object to the preprocess function gives toString result of the passing object ie.

pp.preprocess('var foo = "/* @echo foo */" ', { foo : { bar : 42 }}, 'js');
//  result is 'var foo = "[object Object]"'

What about provide json value of an object ?

mreis1 commented 8 years ago

Hello guys, is there a solution for this problem? This type of functionality seems to me very useful specially when used from grunt-process where there's the need to replace JSON configuration files.

I went into the code to check were "@echo foo" where foo is a javascript object it's printed as it would be expected.

//at line 180 from preprocess.js
rv = replace(rv, opts.type.echo, function (match, variable) {
    variable = (variable || '').trim();
    // if we are surrounded by quotes, echo as a string
    var stringMatch = variable.match(/^(['"])(.*)\1$/);
    if (stringMatch) return stringMatch[2];
    var value = getDeepPropFromObj(context, (variable || '').trim());
    if (typeof value === "object") return JSON.stringify(value); //this will fix the problem
    return value;
  });

running the tests everything goes ok except on context.spec.js 1) preprocess context in nested cases and maintain backwards compatibility:

it('and maintain backwards compatibility', function () {
      input = "// @echo FOO";
      pp.preprocess(input, context, 'js').should.equal("[object Object]");
});```

From my side I don't see where "[object Object]" would be a desirable output