Skip to content

Instantly share code, notes, and snippets.

@swissmanu
Created March 21, 2019 07:19
Show Gist options
  • Save swissmanu/1c82b173da8559cdc6334c147953c47c to your computer and use it in GitHub Desktop.
Save swissmanu/1c82b173da8559cdc6334c147953c47c to your computer and use it in GitHub Desktop.
Apply Prettier Schematic
import { Rule, Tree } from '@angular-devkit/schematics';
import * as prettier from 'prettier';
import { Observable } from 'rxjs';
export default function(): Rule {
return (tree: Tree) =>
new Observable<Tree>(o => {
prettier.resolveConfig(process.cwd()).then(prettierConfig => {
if (!prettierConfig) {
o.error(new Error('Could not resolve prettier configuration'));
return;
}
tree.visit(path => {
if (path.endsWith('.tsx') || path.endsWith('.ts') || path.endsWith('.jsx') || path.endsWith('.js')) {
const content = tree.read(path);
if (content) {
const formatted = prettier.format(content.toString(), prettierConfig);
tree.overwrite(path, formatted);
}
}
return false;
});
o.next(tree);
o.complete();
});
});
}
{
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"apply-prettier": {
"factory": "./apply-prettier/index",
"description": "Applies prettier to a tree of files",
"private": true
}
}
}
// Simple Usage Example
import { strings } from '@angular-devkit/core';
import {
apply,
chain,
filter,
mergeWith,
noop,
Rule,
schematic,
SchematicContext,
template,
Tree,
url
} from '@angular-devkit/schematics';
import { Schema as Options } from './schema';
export default function(options: Options): Rule {
return chain([
(_tree: Tree, _context: SchematicContext) => {
const templateSource = apply(url('./files'), [
template({
...strings,
...options
}),
schematic('apply-prettier', {}) // <- ❤️
]);
return mergeWith(templateSource);
}
]);
}
@swissmanu
Copy link
Author

@keawade nice! thanks for you amendment :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment