Skip to content

Commit

Permalink
Add ability to transfer compilation errors into runtime.
Browse files Browse the repository at this point in the history
  • Loading branch information
rwjblue committed May 6, 2020
1 parent ee12993 commit bdbe63a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
16 changes: 16 additions & 0 deletions __tests__/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,22 @@ describe('htmlbars-inline-precompile', function() {
`);
});

it('avoids a build time error when passed `insertRuntimeErrors`', function() {
precompile = () => {
throw new Error('NOOOOOOOOOOOOOOOOOOOOOO');
};

let transformed = transform(
`import hbs from 'htmlbars-inline-precompile';\nvar compiled = hbs('hello', { insertRuntimeErrors: true });`
);

expect(transformed).toMatchInlineSnapshot(`
"var compiled = function () {
throw new Error(\\"NOOOOOOOOOOOOOOOOOOOOOO\\");
}();"
`);
});

it('escapes any */ included in the template string', function() {
let transformed = transform(stripIndent`
import hbs from 'htmlbars-inline-precompile';
Expand Down
17 changes: 16 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
module.exports = function(babel) {
let t = babel.types;

const runtimeErrorIIFE = babel.template(`(function() {
throw new Error('ERROR_MESSAGE');
})();`);

function buildExpression(value) {
switch (typeof value) {
case 'string':
Expand Down Expand Up @@ -88,7 +92,18 @@ module.exports = function(babel) {
function compileTemplate(precompile, template, _options) {
let options = Object.assign({ contents: template }, _options);

let precompileResult = precompile(template, options);
let precompileResult;

if (options.insertRuntimeErrors) {
try {
precompileResult = precompile(template, options);
} catch (error) {
return runtimeErrorIIFE({ ERROR_MESSAGE: error.message });
}
} else {
precompileResult = precompile(template, options);
}

let precompiled = JSON.parse(precompileResult);

let templateExpression = buildExpression(precompiled);
Expand Down

0 comments on commit bdbe63a

Please sign in to comment.