Skip to content

Commit

Permalink
fix: do not swallow prettier.format errors (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
dpilch authored and alharris-at committed Feb 25, 2022
1 parent fe26cca commit 628a5cc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`react-studio-template-renderer-helper formatCode does not swallow prettier errors 1`] = `"Failed to format"`;

exports[`react-studio-template-renderer-helper formatCode formats code when prettier is installed 1`] = `
"const foo = 1;
const bar = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,5 +114,15 @@ describe('react-studio-template-renderer-helper', () => {

expect(formatCode(code)).toEqual(code);
});

it('does not swallow prettier errors', () => {
jest.mock('prettier', () => ({
format: jest.fn(() => {
throw new Error('Failed to format');
}),
}));

expect(() => formatCode(code)).toThrowErrorMatchingSnapshot();
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -187,16 +187,19 @@ export function bindingPropertyUsesHook(

// optional import prettier
export function formatCode(code: string): string {
let prettier = null;
let parserTypescript = null;

try {
// eslint-disable-next-line global-require, import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
const prettier = require('prettier');
prettier = require('prettier');
// eslint-disable-next-line global-require, import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
const parserTypescript = require('prettier/parser-typescript');

if (prettier && parserTypescript) {
return prettier.format(code, { parser: 'typescript', plugins: [parserTypescript] });
}
parserTypescript = require('prettier/parser-typescript');
} catch {} // eslint-disable-line no-empty

if (prettier && parserTypescript) {
return prettier.format(code, { parser: 'typescript', plugins: [parserTypescript] });
}

return code;
}

0 comments on commit 628a5cc

Please sign in to comment.