Created
March 21, 2019 07:19
-
-
Save swissmanu/1c82b173da8559cdc6334c147953c47c to your computer and use it in GitHub Desktop.
Apply Prettier Schematic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}); | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"$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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@keawade nice! thanks for you amendment :)