Skip to content

Commit

Permalink
Merge pull request #216 from ember-cli/do-not-assume-json-precompile-…
Browse files Browse the repository at this point in the history
…result
  • Loading branch information
rwjblue committed May 7, 2020
2 parents 2242d43 + e273766 commit c1006b6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 42 deletions.
18 changes: 18 additions & 0 deletions __tests__/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,24 @@ describe('htmlbars-inline-precompile', function () {
];
});

it('supports compilation that returns a non-JSON.parseable object', function () {
precompile = (template) => {
return `function() { return "${template}"; }`;
};

let transpiled = transform(
"import hbs from 'htmlbars-inline-precompile';\nvar compiled = hbs`hello`;"
);

expect(transpiled).toMatchInlineSnapshot(`
"var compiled = Ember.HTMLBars.template(
/*
hello
*/
function() { return \\"hello\\"; });"
`);
});

it('passes options when used as a call expression', function () {
let source = 'hello';
transform(`import hbs from 'htmlbars-inline-precompile';\nvar compiled = hbs('${source}');`);
Expand Down
46 changes: 4 additions & 42 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,7 @@ module.exports = function (babel) {
const runtimeErrorIIFE = babel.template(
`(function() {\n throw new Error('ERROR_MESSAGE');\n})();`
);

function buildExpression(value) {
switch (typeof value) {
case 'string':
return t.stringLiteral(value);
case 'number':
return t.numberLiteral(value);
case 'boolean':
return t.booleanLiteral(value);
case 'object': {
if (Array.isArray(value)) {
return buildArrayExpression(value);
} else {
return buildObjectExpression(value);
}
}
default:
throw new Error(
`hbs compilation error; unexpected type from precompiler: ${typeof value} for ${JSON.stringify(
value
)}`
);
}
}

function buildObjectExpression(object) {
let properties = [];
for (let key in object) {
let value = object[key];

properties.push(t.objectProperty(t.identifier(key), buildExpression(value)));
}

return t.objectExpression(properties);
}

function buildArrayExpression(array) {
return t.arrayExpression(array.map((i) => buildExpression(i)));
}
const parsePrecompiledTemplate = babel.template('PRECOMPILED');

function parseExpression(buildError, node) {
switch (node.type) {
Expand Down Expand Up @@ -104,9 +66,9 @@ module.exports = function (babel) {
precompileResult = precompile(template, options);
}

let precompiled = JSON.parse(precompileResult);

let templateExpression = buildExpression(precompiled);
let templateExpression = parsePrecompiledTemplate({
PRECOMPILED: precompileResult,
}).expression;

t.addComment(
templateExpression,
Expand Down

0 comments on commit c1006b6

Please sign in to comment.