Skip to content

Instantly share code, notes, and snippets.

@bennycode
Last active September 14, 2018 15:23
Show Gist options
  • Save bennycode/16f15dd1dfa254b08676840ec3e3ed10 to your computer and use it in GitHub Desktop.
Save bennycode/16f15dd1dfa254b08676840ec3e3ed10 to your computer and use it in GitHub Desktop.
Use Prettier API (Node.js)
const fs = require('fs');
const glob = require('glob');
const prettier = require('prettier');
const path = require('path');
// equivalent to "prettier --ignore-path .gitignore "**/*.{json,md,scss}" --list-different"
const editorConfig = path.join(process.cwd(), '.editorconfig');
const filePattern = '**/*.{json,md,scss}';
const gitIgnore = path.join(process.cwd(), '.gitignore');
glob(filePattern, undefined, async (globError, files) => {
if (globError) {
throw globError;
}
const hasEditorConfig = fs.existsSync(editorConfig) ? true : false;
const resolvingOptions = {
editorconfig: hasEditorConfig,
useCache: true
};
const formattingOptions = await prettier.resolveConfig(process.cwd(), resolvingOptions);
files.forEach(async fileName => {
const filePath = fileName;
const fileInfoOptions = {
ignorePath: gitIgnore,
withNodeModules: false
};
const fileInfo = await prettier.getFileInfo(filePath, fileInfoOptions);
if (fileInfo.ignored) {
console.log(`Skipping file "${filePath}"...`);
return;
}
console.log(`Processing file "${filePath}"...`);
formattingOptions.parser = fileInfo.inferredParser;
const sourceCode = fs.readFileSync(filePath, 'utf8');
const isPretty = prettier.check(sourceCode, formattingOptions);
if (!isPretty) {
const formatted = prettier.format(sourceCode, formattingOptions);
fs.writeFileSync(filePath, formatted, {encoding: 'utf8'});
console.log(`Formatted file "${filePath}"`);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment