npm install --save-dev @bdchauvette/gulp-prettier
prettier
is a peer dependency, so make sure to install it if it's not already in your package.json
:
npm install --save-dev prettier
const gulp = require("gulp");
const prettier = require("@bdchauvette/gulp-prettier");
gulp.task("prettify", () =>
gulp
.src("src/**/*.js")
.pipe(
prettier({
// Normal prettier options, e.g.:
singleQuote: true,
trailingComma: "all"
})
)
.pipe(gulp.dest(file => file.base))
);
The plugin adds a boolean didPrettierFormat
property to the Vinyl file
object. You can use this property to only output changed files, or fail CI
builds if any files were not changed (see recipes below).
For the available options, see the
prettier
documentation.
The only option that is not passed directly through to prettier
is filepath
.
This plugin overrides the filepath
property to match the path
property of
the Vinyl File object being formatted. This allows prettier
to infer which
parser to use if you do not explicitly set the parser
option.
For example, if you use gulp.src('**/*.css')
, prettier
will automatically
infer that it needs to use the postcss
parser to format your stylesheets.
If you only want to write files that have actually been changed, you can use
gulp-filter
to filter out files that were already correctly formatted.
const gulp = require("gulp");
const filter = require("gulp-filter");
const prettier = require("@bdchauvette/gulp-prettier");
gulp.task("prettify", () =>
gulp
.src("src/**/*.js")
.pipe(prettier())
.pipe(filter(file => file.didPrettierFormat))
.pipe(gulp.dest(file => file.base))
);
In a CI environment, you might want to fail the build if you detect any files
that haven't been formatted by prettier. You can do this by using gulp-if
to pipe to gulp-error
if any files are freshly formatted (i.e. they have the didPrettierFormat
property).
const gulp = require("gulp");
const gulpError = require("gulp-error");
const gulpIf = require("gulp-if");
const isCI = require("is-ci");
const prettier = require("@bdchauvette/gulp-prettier");
gulp.task("prettify", () =>
gulp
.src("src/**/*.js")
.pipe(prettier())
.pipe(gulpIf(file => isCI && file.didPrettierFormat, gulpError()))
.pipe(gulp.dest(file => file.base))
);
If you would like to use a custom build of prettier
, e.g.
prettier-miscellaneous
, you can require
@bdchauvette/gulp-prettier/factory
, then pass it your own version of
prettier
:
const gulp = require("gulp");
const customPrettier = require("prettier-miscellaneous");
const createGulpPrettier = require("@bdchauvette/gulp-prettier/factory");
const gulpPrettier = createGulpPrettier(customPrettier);
gulp.task("prettify", () =>
gulp
.src("src/**/*.js")
.pipe(gulpPrettier({ singleQuote: true }))
.pipe(gulp.dest(file => file.base))
);
prettier
does not currently support sourcemaps, so neither does this
plugin.
See #445 and #2073 for discussion.
There are a few different projects that integrate prettier
and gulp
:
npm test
npm run lint
# With fixes
npm run lint:fix