Skip to content

Commit

Permalink
feat(prettier): Forward all text to prettier
Browse files Browse the repository at this point in the history
If we forward all text with it's filepath if there is one, prettier will figure out which parser it should use. This will make this package support all future parsers prettier till add in the future by default.

We only have to check which files to forward to eslint which is something that changes less frequently. For now we forward files with extension defined in eslint config or default to .js/.jsx/.ts/.tsx files.
  • Loading branch information
zimme committed Dec 19, 2017
1 parent d2cd8b3 commit 251cc91
Showing 1 changed file with 15 additions and 21 deletions.
36 changes: 15 additions & 21 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function format(options) {

const prettierOptions = merge(
{},
filePath && { filepath: filePath },
getPrettierConfig(filePath, prettierPath),
options.prettierOptions
);
Expand All @@ -85,35 +86,28 @@ function format(options) {
})
);

const isCss = /\.(css)$/.test(filePath);
const isLess = /\.(less)$/.test(filePath);
const isScss = /\.(scss)$/.test(filePath);
const isTypeScript = /\.(ts|tsx)$/.test(filePath);
const isGraphQL = /\.(graphql|gql)$/.test(filePath);
const isJson = /\.json$/.test(filePath);
const eslintExtensions = eslintConfig.extensions || [
".js",
".jsx",
".ts",
".tsx"
];
const eslintExtensionsRegex = new RegExp(eslintExtensions.join("|"), "gi");

if (isCss) {
formattingOptions.prettier.parser = "css";
} else if (isLess) {
formattingOptions.prettier.parser = "less";
} else if (isScss) {
formattingOptions.prettier.parser = "scss";
} else if (isTypeScript) {
formattingOptions.prettier.parser = "typescript";
// If we don't get filePath run eslint on text, otherwise only run eslint
// if it's a configured extension or fall back to a "supported" file type.
const onlyPrettier = filePath ? !eslintExtensionsRegex.test(filePath) : false;

if (/\.tsx?$/.test(filePath)) {
// XXX: It seems babylon is getting a TypeScript plugin.
// Should that be used instead?
formattingOptions.eslint.parser = "typescript-eslint-parser";
} else if (isGraphQL) {
formattingOptions.prettier.parser = "graphql";
} else if (isJson) {
formattingOptions.prettier.parser = "json";
formattingOptions.prettier.trailingComma = "none";
}

const prettify = createPrettify(formattingOptions.prettier, prettierPath);

if (isCss || isLess || isScss || isGraphQL || isJson) {
return prettify(text, filePath);
if (onlyPrettier) {
return prettify(text);
}

const eslintFix = createEslintFix(formattingOptions.eslint, eslintPath);
Expand Down

0 comments on commit 251cc91

Please sign in to comment.