chore: setup markdown formatting (#3224)

* chore(deps): upgrade prettier to v1.8.2

* chore: setup lint-docs script

* docs: add `<!-- prettier-ignore -->`s

* docs: format docs

* Revert "docs: format docs"

This reverts commit 6dba903987dddc498cb589ca311905f25b6aee53.

* chore(prettierrc): set `--no-prose-wrap`

* docs: format docs

* Revert "docs: format docs"

This reverts commit 139bd744b6921916be8fac4fa3bab83bae5d12df.

* docs: tweak

* docs: format docs

* chore: rename .prettierrc

* chore: rename back to .prettierrc

* chore: split out third-party

* refactor: fix linting

* chore: do not split out third-party on website
master
Ika 2017-11-22 19:27:40 +08:00 committed by Lucas Azzola
parent a0c95cf862
commit 76efb33e75
35 changed files with 525 additions and 436 deletions

3
.prettierrc Normal file
View File

@ -0,0 +1,3 @@
{
"proseWrap": false
}

View File

@ -20,6 +20,7 @@ before_script:
- if [ "${NODE_ENV}" = "production" ]; then yarn build; fi
script:
- yarn lint
- yarn lint-docs
- AST_COMPARE=1 yarn test -- --runInBand
- if [ "${NODE_ENV}" = "development" ]; then yarn codecov; fi
deploy:

View File

@ -134,6 +134,7 @@
* Fix website on iOS Safari (#1970)
Formatting change:
* Position JSX whitespace (`{" "}`) at the end of lines (#1964)
Lots of small fixes, mainly for TypeScript.
@ -209,7 +210,7 @@ Lots of small fixes, mainly for TypeScript.
* Add space around `=` for flow generics default arguments (#1476)
* Don't break for unparenthesised single argument flow function (#1452)
* Don't break on empty arrays and objects (#1440)
* Do not break on [0] (#1441)
* Do not break on `[0]` (#1441)
* Reorder flow object props (#1451)
* Break inline object first in function arguments (#1453)
* Break inline object first in function arguments (#1453) (#1173)
@ -308,7 +309,7 @@ Lots of small fixes, mainly for TypeScript.
* [JSX] Break if opening element breaks (#942)
* Parenthesize function expressions in expression position (#941)
* update the README to add a pre-commit hook (#944)
* Fix #951: properly parenthesize ** expressions (#952)
* Fix #951: properly parenthesize \** expressions (#952)
* [WIP] TypeScript Parser (#915)
* Do not break long `describe` calls (#953)
* Recursively find leading comments inside ReturnStatements (#955)
@ -578,50 +579,50 @@ Lots of small fixes, mainly for TypeScript.
Now using minor versions instead of patch versions for the releases.
* Swap quotes (#355)
* Drop jsesc (#357)
* Use a Symbol instead of the private dep (#359)
* Add parens for default export FunctionExpressions (#345)
* Fix export extension output (#361)
* Exit with an error if an unknown CLI option is passed (#365)
* Warn if using deprecated CLI options (#364)
* s/jscodefmt/prettier/ (#370)
* Fix CLI options (#369)
* Fix some parens cases for UpdateExpressions (#381)
* Output strings with the minimum amount of escaped quotes (#390)
* Ignore EmptyStatement inside of switch case (#391)
* Support multiple standalones in import (#389)
* Fix missing semi-colon in for loop and var body (#388)
* Fix empty labels (#383)
* Fix forced trailing comma (#382)
* Empty switch should not have an empty line (#384)
* add formatAST() for formatting ASTs directly (#393)
* Fix class extends parenthesis (#396)
* Fix class inside of binary expression missing parenthesis (#397)
* Fix parenthesis in object as left-hand-side of template (#398)
* Remove unneeded parens for FunctionExpression inside LogicalExpression (#399)
* Remove trailing comma for array destructuring with rest (#400)
* Fix +++x (#401)
* Also do the class extend parenthesis for class expressions (#403)
* Fix various parenthesis issues on the left side of template (#404)
* Fix in inside of the first group of a for (#406)
* Add parenthesis for arrow function inside of ternary (#408)
* Add parenthesis around class expression when left side of call expression (#409)
* Ensure computed method names don't lose quotes (#419)
* Add parenthesis for yield inside of a conditional (#418)
* Add parenthesis around assignment for arrow function body (#422)
* Add parenthesis around export default assignments (#423)
* Add parenthesis for class expression on left of member expression (#421)
* Fix missing parens around object in MemberExpression (#424)
* Re-run snapshot tests
* Workaround flow bug around trailing comma (#427)
* Add parenthesis when class expressions are left of a ternary (#428)
* Revert "Workaround flow bug around trailing comma" (#429)
* Update commands.md (#430)
* Improve vim integration section (#416)
* Add glob support to the CLI (#363)
* Use babel-code-frame for syntax errors (#367)
* Update yarn.lock
* Swap quotes (#355)
* Drop jsesc (#357)
* Use a Symbol instead of the private dep (#359)
* Add parens for default export FunctionExpressions (#345)
* Fix export extension output (#361)
* Exit with an error if an unknown CLI option is passed (#365)
* Warn if using deprecated CLI options (#364)
* s/jscodefmt/prettier/ (#370)
* Fix CLI options (#369)
* Fix some parens cases for UpdateExpressions (#381)
* Output strings with the minimum amount of escaped quotes (#390)
* Ignore EmptyStatement inside of switch case (#391)
* Support multiple standalones in import (#389)
* Fix missing semi-colon in for loop and var body (#388)
* Fix empty labels (#383)
* Fix forced trailing comma (#382)
* Empty switch should not have an empty line (#384)
* add formatAST() for formatting ASTs directly (#393)
* Fix class extends parenthesis (#396)
* Fix class inside of binary expression missing parenthesis (#397)
* Fix parenthesis in object as left-hand-side of template (#398)
* Remove unneeded parens for FunctionExpression inside LogicalExpression (#399)
* Remove trailing comma for array destructuring with rest (#400)
* Fix +++x (#401)
* Also do the class extend parenthesis for class expressions (#403)
* Fix various parenthesis issues on the left side of template (#404)
* Fix in inside of the first group of a for (#406)
* Add parenthesis for arrow function inside of ternary (#408)
* Add parenthesis around class expression when left side of call expression (#409)
* Ensure computed method names don't lose quotes (#419)
* Add parenthesis for yield inside of a conditional (#418)
* Add parenthesis around assignment for arrow function body (#422)
* Add parenthesis around export default assignments (#423)
* Add parenthesis for class expression on left of member expression (#421)
* Fix missing parens around object in MemberExpression (#424)
* Re-run snapshot tests
* Workaround flow bug around trailing comma (#427)
* Add parenthesis when class expressions are left of a ternary (#428)
* Revert "Workaround flow bug around trailing comma" (#429)
* Update commands.md (#430)
* Improve vim integration section (#416)
* Add glob support to the CLI (#363)
* Use babel-code-frame for syntax errors (#367)
* Update yarn.lock
# 0.0.10
@ -744,7 +745,7 @@ Now using minor versions instead of patch versions for the releases.
* remove unused recast ref
* Fix typo in README.
* Support type annotation for rest argument on babylon parser
* Use `setq' instead of `infc' and `decf'
* Use `setq` instead of `infc` and `decf`
* Add title and encoding to the REPL
* Fix old name reference in tests_config
* Minimize string escapes

View File

@ -11,30 +11,14 @@ yarn test
Here's what you need to know about the tests:
* The tests uses [Jest](https://facebook.github.io/jest/) snapshots.
* You can make changes and run `jest -u` (or `yarn test -u`) to update the
snapshots. Then run `git diff` to take a look at what changed. Always update
the snapshots when opening a PR.
* You can run `AST_COMPARE=1 jest` for a more robust test run. That formats each
file, re-parses it, and compares the new AST with the original one and makes
sure they are semantically equivalent.
* Each test folder has a `jsfmt.spec.js` that runs the tests. Normally you can
just put `run_spec(__dirname);` there. You can also pass options and
additional parsers, like this:
`run_spec(__dirname, { trailingComma: "es5" }, ["babylon"]);`
* `tests/flow/` contains the Flow test suite, and is not supposed to be edited
by hand. To update it, clone the Flow repo next to the Prettier repo and run:
`node scripts/sync-flow-tests.js ../flow/tests/`.
* If you would like to debug prettier locally, you can either debug it in node
or the browser. The easiest way to debug it in the browser is to run the
interactive `docs` REPL locally. The easiest way to debug it in node, is to
create a local test file and run it in an editor like VS Code.
* You can make changes and run `jest -u` (or `yarn test -u`) to update the snapshots. Then run `git diff` to take a look at what changed. Always update the snapshots when opening a PR.
* You can run `AST_COMPARE=1 jest` for a more robust test run. That formats each file, re-parses it, and compares the new AST with the original one and makes sure they are semantically equivalent.
* Each test folder has a `jsfmt.spec.js` that runs the tests. Normally you can just put `run_spec(__dirname);` there. You can also pass options and additional parsers, like this: `run_spec(__dirname, { trailingComma: "es5" }, ["babylon"]);`
* `tests/flow/` contains the Flow test suite, and is not supposed to be edited by hand. To update it, clone the Flow repo next to the Prettier repo and run: `node scripts/sync-flow-tests.js ../flow/tests/`.
* If you would like to debug prettier locally, you can either debug it in node or the browser. The easiest way to debug it in the browser is to run the interactive `docs` REPL locally. The easiest way to debug it in node, is to create a local test file and run it in an editor like VS Code.
Run `yarn lint --fix` to automatically format files.
If you can, take look at [commands.md](commands.md) and check out [Wadler's
paper](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf) to
understand how Prettier works.
If you can, take look at [commands.md](commands.md) and check out [Wadler's paper](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf) to understand how Prettier works.
If you want to know more about Prettier's GitHub labels, see the
[Issue Labels](https://github.com/prettier/prettier/wiki/Issue-Labels)
page on the Wiki.
If you want to know more about Prettier's GitHub labels, see the [Issue Labels](https://github.com/prettier/prettier/wiki/Issue-Labels) page on the Wiki.

View File

@ -39,12 +39,11 @@
## Intro
Prettier is an opinionated code formatter. It enforces a consistent style by
parsing your code and re-printing it with its own rules that take the maximum
line length into account, wrapping code when necessary.
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
### Input
<!-- prettier-ignore -->
```js
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
@ -60,16 +59,13 @@ foo(
);
```
Prettier can be ran [in your editor](http://prettier.io/docs/en/editors.html)
on-save, in a [pre-commit hook](https://prettier.io/docs/en/precommit.html),
or in [CI environments](https://prettier.io/docs/en/cli.html#list-different)
to ensure your codebase has a consistent style without devs ever having to post
a nit comment on a code review ever again!
Prettier can be ran [in your editor](http://prettier.io/docs/en/editors.html) on-save, in a [pre-commit hook](https://prettier.io/docs/en/precommit.html), or in [CI environments](https://prettier.io/docs/en/cli.html#list-different) to ensure your codebase has a consistent style without devs ever having to post a nit comment on a code review ever again!
- - -
---
**[Documentation](https://prettier.io/docs/en/)**
<!-- prettier-ignore -->
[Install](https://prettier.io/docs/en/install.html) ·
[Options](https://prettier.io/docs/en/options.html) ·
[CLI](https://prettier.io/docs/en/cli.html) ·
@ -77,11 +73,11 @@ a nit comment on a code review ever again!
**[Playground](https://prettier.io/playground/)**
- - -
---
## Badge
Show the world you're using *Prettier* → [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
Show the world you're using _Prettier_ → [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
```md
[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)

View File

@ -1,8 +1,4 @@
The core of the algorithm is implemented in `doc-{printer,builders,utils,debug}.js`. The printer should
use the basic formatting abstractions provided to construct a format
when printing a node. Parts of the API only exist to be compatible
with recast's previous API to ease migration, but over time we can
clean it up.
The core of the algorithm is implemented in `doc-{printer,builders,utils,debug}.js`. The printer should use the basic formatting abstractions provided to construct a format when printing a node. Parts of the API only exist to be compatible with recast's previous API to ease migration, but over time we can clean it up.
The following commands are available:
@ -12,29 +8,20 @@ Combine an array into a single string.
### group
Mark a group of items which the printer should try to fit on one line.
This is the basic command to tell the printer when to break. Groups
are usually nested, and the printer will try to fit everything on one
line, but if it doesn't fit it will break the outermost group first
and try again. It will continue breaking groups until everything fits
(or there are no more groups to break).
Mark a group of items which the printer should try to fit on one line. This is the basic command to tell the printer when to break. Groups are usually nested, and the printer will try to fit everything on one line, but if it doesn't fit it will break the outermost group first and try again. It will continue breaking groups until everything fits (or there are no more groups to break).
A document can force parent groups to break by including `breakParent`
(see below). A hard and literal line automatically include this so
they always break parent groups. Breaks are propagated to all parent
groups, so if a deeply nested expression has a hard break, everything
with break. This only matters for "hard" breaks, i.e. newlines that
are printed no matter what and can be statically analyzed.
A document can force parent groups to break by including `breakParent` (see below). A hard and literal line automatically include this so they always break parent groups. Breaks are propagated to all parent groups, so if a deeply nested expression has a hard break, everything with break. This only matters for "hard" breaks, i.e. newlines that are printed no matter what and can be statically analyzed.
For example, an array will try to fit on one line:
<!-- prettier-ignore -->
```js
[1, "foo", { bar: 2 }]
```
However, if any of the items inside the array have a hard break, the
array will *always* break as well:
However, if any of the items inside the array have a hard break, the array will _always_ break as well:
<!-- prettier-ignore -->
```js
[
1,
@ -45,14 +32,13 @@ array will *always* break as well:
]
```
Functions always break after the opening curly brace no matter what,
so the array breaks as well for consistent formatting. See the
implementation of `ArrayExpression` for an example.
Functions always break after the opening curly brace no matter what, so the array breaks as well for consistent formatting. See the implementation of `ArrayExpression` for an example.
### conditionalGroup
This should be used as **last resort** as it triggers an exponential complexity when nested. This will try to print the first argument, if it fit use it, otherwise go to the next one and so on.
<!-- prettier-ignore -->
```js
conditionalGroup([a, b, c])
```
@ -61,24 +47,25 @@ conditionalGroup([a, b, c])
This is an alternative type of group which behave like text layout: it's going to add a break whenever the next element doesn't fit in the line anymore. The difference with a typical group is that it's not going to break all the separators, just the ones that are at the end of lines.
<!-- prettier-ignore -->
```js
fill(["I", line, "love", line, "prettier"])
```
### ifBreak
Prints something if the current group breaks and something else if it doesn't.
<!-- prettier-ignore -->
```js
ifBreak(";", " ")
```
### breakParent
Include this anywhere to force all parent groups to break. See `group`
for more info. Example:
Include this anywhere to force all parent groups to break. See `group` for more info. Example:
<!-- prettier-ignore -->
```js
group(
concat([
@ -96,35 +83,32 @@ Join an array of items with a separator.
### line
Specify a line break. If an expression fits on one line, the line
break will be replaced with a space. Line breaks always indent the
next line with the current level of indentation.
Specify a line break. If an expression fits on one line, the line break will be replaced with a space. Line breaks always indent the next line with the current level of indentation.
### softline
Specify a line break. The difference from `line` is that if the
expression fits on one line, it will be replaced with nothing.
Specify a line break. The difference from `line` is that if the expression fits on one line, it will be replaced with nothing.
### hardline
Specify a line break that is **always** included in the output, no
matter if the expression fits on one line or not.
Specify a line break that is **always** included in the output, no matter if the expression fits on one line or not.
### literalline
Specify a line break that is **always** included in the output, and
don't indent the next line. This is used for template literals.
Specify a line break that is **always** included in the output, and don't indent the next line. This is used for template literals.
### lineSuffix
This is used to implement trailing comments. In practice, it is not practical to find where the line ends and you don't want to accidentally print some code at the end of the comment. `lineSuffix` will buffer the output and flush it before any new line.
<!-- prettier-ignore -->
```js
concat(["a", lineSuffix(" // comment"), ";", hardline])
```
will output
<!-- prettier-ignore -->
```js
a; // comment
```
@ -133,12 +117,14 @@ a; // comment
In cases where you embed code inside of templates, comments shouldn't be able to leave the code part. lineSuffixBoundary is an explicit marker you can use to flush code in addition to newlines.
<!-- prettier-ignore -->
```js
concat(["{", lineSuffix(" // comment"), lineSuffixBoundary, "}", hardline])
```
will output
<!-- prettier-ignore -->
```js
{ // comment
}
@ -146,6 +132,7 @@ will output
and **not**
<!-- prettier-ignore -->
```js
{} // comment
```
@ -166,6 +153,7 @@ This is a placeholder value where the cursor is in the original input in order t
For an example, here's the implementation of the `ArrayExpression` node type:
<!-- prettier-ignore -->
```js
group(
concat([
@ -186,6 +174,4 @@ group(
)
```
This is a group with opening and closing brackets, and possibly
indented contents. Because it's a `group` it will always be
broken up if any of the sub-expressions are broken.
This is a group with opening and closing brackets, and possibly indented contents. Because it's a `group` it will always be broken up if any of the sub-expressions are broken.

View File

@ -18,13 +18,11 @@ prettier.format("foo ( );", { semi: false });
## `prettier.check(source [, options])`
`check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`.
This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
`check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`. This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios.
## `prettier.formatWithCursor(source [, options])`
`formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code.
This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
`formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code. This is useful for editor integrations, to prevent the cursor from moving when code is formatted.
The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`.
@ -35,11 +33,8 @@ prettier.formatWithCursor(" 1", { cursorOffset: 2 });
## `prettier.resolveConfig(filePath [, options])`
`resolveConfig` can be used to resolve configuration for a given source file, passing its path as the first argument.
The config search will start at the file path and continue to search up the directory (you can use `process.cwd()` to start
searching from the current directory).
Or you can pass directly the path of the config file as `options.config` if you don't wish to search for it.
A promise is returned which will resolve to:
`resolveConfig` can be used to resolve configuration for a given source file, passing its path as the first argument. The config search will start at the file path and continue to search up the directory (you can use `process.cwd()` to start searching from the current directory). Or you can pass directly the path of the config file as `options.config` if you don't wish to search for it. A promise is returned which will resolve to:
* An options object, providing a [config file](configuration.md) was found.
* `null`, if no file was found.
@ -51,24 +46,20 @@ If `options.useCache` is `false`, all caching will be bypassed.
const text = fs.readFileSync(filePath, "utf8");
prettier.resolveConfig(filePath).then(options => {
const formatted = prettier.format(text, options);
})
});
```
Use `prettier.resolveConfig.sync(filePath [, options])` if you'd like to use sync version.
## `prettier.clearConfigCache()`
As you repeatedly call `resolveConfig`, the file system structure will be cached for performance.
This function will clear the cache. Generally this is only needed for editor integrations that
know that the file system has changed since the last format took place.
As you repeatedly call `resolveConfig`, the file system structure will be cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
## `prettier.getSupportInfo([version])`
Returns an object representing the parsers, languages and file types Prettier
supports.
Returns an object representing the parsers, languages and file types Prettier supports.
If `version` is provided (e.g. `"1.5.0"`), information for that version will be
returned, otherwise information for the current version will be returned.
If `version` is provided (e.g. `"1.5.0"`), information for that version will be returned, otherwise information for the current version will be returned.
The support information looks like this:
@ -95,6 +86,7 @@ The support information looks like this:
## Custom Parser API
If you need to make modifications to the AST (such as codemods), or you want to provide an alternate parser, you can do so by setting the `parser` option to a function. The function signature of the parser function is:
```js
(text: string, parsers: object, options: object) => AST;
```

View File

@ -3,11 +3,9 @@ id: cli
title: CLI
---
Run Prettier through the CLI with this script. Run it without any
arguments to see the [options](options.md).
Run Prettier through the CLI with this script. Run it without any arguments to see the [options](options.md).
To format a file in-place, use `--write`. You may want to consider
committing your code before doing that, just in case.
To format a file in-place, use `--write`. You may want to consider committing your code before doing that, just in case.
```bash
prettier [opts] [filename ...]
@ -19,24 +17,17 @@ In practice, this may look something like:
prettier --single-quote --trailing-comma es5 --write "{app,__{tests,mocks}__}/**/*.js"
```
Don't forget the quotes around the globs! The quotes make sure that Prettier
expands the globs rather than your shell, for cross-platform usage.
The [glob syntax from the glob module](https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer)
is used.
Don't forget the quotes around the globs! The quotes make sure that Prettier expands the globs rather than your shell, for cross-platform usage. The [glob syntax from the glob module](https://github.com/isaacs/node-glob/blob/master/README.md#glob-primer) is used.
Prettier CLI will ignore files located in `node_modules` directory. To opt-out from this behavior use `--with-node-modules` flag.
## `--debug-check`
If you're worried that Prettier will change the correctness of your code, add `--debug-check` to the command.
This will cause Prettier to print an error message if it detects that code correctness might have changed.
Note that `--write` cannot be used with `--debug-check`.
If you're worried that Prettier will change the correctness of your code, add `--debug-check` to the command. This will cause Prettier to print an error message if it detects that code correctness might have changed. Note that `--write` cannot be used with `--debug-check`.
## `--find-config-path` and `--config`
If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost
when prettier attempts to look up a [configuration file](configuration.md). In order to skip this, you may
ask prettier to find the config file once, and re-use it later on.
If you are repeatedly formatting individual files with `prettier`, you will incur a small performance cost when prettier attempts to look up a [configuration file](configuration.md). In order to skip this, you may ask prettier to find the config file once, and re-use it later on.
```bash
prettier --find-config-path ./my/file.js
@ -49,19 +40,18 @@ This will provide you with a path to the configuration file, which you can pass
prettier --config ./my/.prettierrc --write ./my/file.js
```
You can also use `--config` if your configuration file lives somewhere where prettier cannot find it,
such as a `config/` directory.
You can also use `--config` if your configuration file lives somewhere where prettier cannot find it, such as a `config/` directory.
If you don't have a configuration file, or want to ignore it if it does exist,
you can pass `--no-config` instead.
If you don't have a configuration file, or want to ignore it if it does exist, you can pass `--no-config` instead.
### `--ignore-path`
Path to a file containing patterns that describe files to ignore. By default, prettier looks for `./.prettierignore`.
Path to a file containing patterns that describe files to ignore. By default, prettier looks for `./.prettierignore`.
## `--require-pragma`
Require a special comment, called a pragma, to be present in the file's first docblock comment in order for prettier to format it.
```js
/**
* @prettier
@ -72,8 +62,7 @@ Valid pragmas are `@prettier` and `@format`.
## `--insert-pragma`
Insert a `@format` pragma to the top of formatted files when pragma is absent.
Works well when used in tandem with `--require-pragma`.
Insert a `@format` pragma to the top of formatted files when pragma is absent. Works well when used in tandem with `--require-pragma`.
## `--list-different`
@ -85,7 +74,7 @@ prettier --single-quote --list-different "src/**/*.js"
## `--no-config`
Do not look for a configuration file. The default settings will be used.
Do not look for a configuration file. The default settings will be used.
## `--config-precedence`
@ -111,4 +100,4 @@ Prettier CLI will ignore files located in `node_modules` directory. To opt-out f
## `--write`
This rewrites all processed files in place. This is comparable to the `eslint --fix` workflow.
This rewrites all processed files in place. This is comparable to the `eslint --fix` workflow.

View File

@ -3,15 +3,13 @@ id: configuration
title: Configuration File
---
Prettier uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file support.
This means you can configure prettier via:
Prettier uses [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for configuration file support. This means you can configure prettier via:
* A `.prettierrc` file, written in YAML or JSON, with optional extensions: `.yaml/.yml/.json/.js`.
* A `prettier.config.js` file that exports an object.
* A `"prettier"` key in your `package.json` file.
The configuration file will be resolved starting from the location of the file being formatted,
and searching up the file tree until a config file is (or isn't) found.
The configuration file will be resolved starting from the location of the file being formatted, and searching up the file tree until a config file is (or isn't) found.
The options to the configuration file are the same as the [API options](options.md).
@ -37,20 +35,21 @@ parser: flow
## Configuration Overrides
Prettier borrows eslint's [override format](http://eslint.org/docs/user-guide/configuring#example-configuration).
This allows you to apply configuration to specific files.
Prettier borrows eslint's [override format](http://eslint.org/docs/user-guide/configuring#example-configuration). This allows you to apply configuration to specific files.
JSON:
```json
{
"semi": false,
"overrides": [{
"files": "*.test.js",
"options": {
"semi": true
"overrides": [
{
"files": "*.test.js",
"options": {
"semi": true
}
}
}]
]
}
```
@ -64,17 +63,18 @@ overrides:
semi: true
```
`files` is required for each override, and may be a string or array of strings.
`excludeFiles` may be optionally provided to exclude files for a given rule, and may also be a string or array of strings.
`files` is required for each override, and may be a string or array of strings. `excludeFiles` may be optionally provided to exclude files for a given rule, and may also be a string or array of strings.
To get prettier to format its own `.prettierrc` file, you can do:
```json
{
"overrides": [{
"files": ".prettierrc",
"options": { "parser": "json" }
}]
"overrides": [
{
"files": ".prettierrc",
"options": { "parser": "json" }
}
]
}
```

View File

@ -5,13 +5,11 @@ title: Editor Integration
## Atom
Atom users can simply install the [prettier-atom](https://github.com/prettier/prettier-atom) package and use
`Ctrl+Alt+F` to format a file (or format on save if enabled).
Atom users can simply install the [prettier-atom](https://github.com/prettier/prettier-atom) package and use `Ctrl+Alt+F` to format a file (or format on save if enabled).
## Emacs
Emacs users should see [this repository](https://github.com/prettier/prettier-emacs)
for on-demand formatting.
Emacs users should see [this repository](https://github.com/prettier/prettier-emacs) for on-demand formatting.
## Vim
@ -31,8 +29,7 @@ Install the [JavaScript Prettier extension](https://github.com/madskristensen/Ja
## Sublime Text
Sublime Text support is available through Package Control and
the [JsPrettier](https://packagecontrol.io/packages/JsPrettier) plug-in.
Sublime Text support is available through Package Control and the [JsPrettier](https://packagecontrol.io/packages/JsPrettier) plug-in.
## JetBrains WebStorm, PHPStorm, PyCharm...

View File

@ -31,7 +31,7 @@ yarn add --dev prettier eslint-plugin-prettier
Whether you run Prettier via ESLint or run both tools separately, you probably only want to hear about each formatting issue once, and you especially don't want ESLint to complain about formatting "issues" which are simply a different preference than what Prettier does.
So you'll probably want to disable the conflicting rules (while keeping around other rules that Prettier doesn't care about). The easiest way to do this is to use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier). It's a one liner that can be added on-top of any existing ESLint configuration.
So you'll probably want to disable the conflicting rules (while keeping around other rules that Prettier doesn't care about). The easiest way to do this is to use [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier). It's a one liner that can be added on-top of any existing ESLint configuration.
```
$ yarn add --dev eslint-config-prettier
@ -41,9 +41,7 @@ $ yarn add --dev eslint-config-prettier
```json
{
"extends": [
"prettier"
]
"extends": ["prettier"]
}
```

View File

@ -11,6 +11,7 @@ A JavaScript comment of `// prettier-ignore` will exclude the next node in the a
For example:
<!-- prettier-ignore -->
```js
matrix(
1, 0, 0,
@ -43,8 +44,8 @@ matrix(
```jsx
<div>
{/* prettier-ignore */}
<span ugly format='' />
{/* prettier-ignore */}
<span ugly format='' />
</div>;
```

View File

@ -14,8 +14,7 @@ Prettier is an opinionated code formatter with support for:
* [GraphQL](http://graphql.org/)
* [Markdown](http://commonmark.org/), including [GFM](https://github.github.com/gfm/)
It removes all original styling[\*](#footnotes) and ensures that all outputted code
conforms to a consistent style. (See this [blog post](http://jlongster.com/A-Prettier-Formatter))
It removes all original styling[\*](#footnotes) and ensures that all outputted code conforms to a consistent style. (See this [blog post](http://jlongster.com/A-Prettier-Formatter))
Prettier takes your code and reprints it from scratch by taking the line length into account.
@ -27,6 +26,7 @@ foo(arg1, arg2, arg3, arg4);
It fits in a single line so it's going to stay as is. However, we've all run into this situation:
<!-- prettier-ignore -->
```js
foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne());
```
@ -52,9 +52,7 @@ If you want to learn more, these two conference talks are great introductions:
#### Footnotes
\* _Well actually, some original styling is preserved when practical—see
[empty lines] and [multi-line objects]._
\* _Well actually, some original styling is preserved when practical—see [empty lines] and [multi-line objects]._
[empty lines]:rationale.md#empty-lines
[multi-line objects]:rationale.md#multi-line-objects
[empty lines]: rationale.md#empty-lines
[multi-line objects]: rationale.md#multi-line-objects

View File

@ -15,7 +15,7 @@ You can install it globally if you like:
yarn global add prettier
```
*We're using `yarn` but you can use `npm` if you like:*
_We're using `yarn` but you can use `npm` if you like:_
```
npm install --save-dev --save-exact prettier
@ -23,5 +23,4 @@ npm install --save-dev --save-exact prettier
npm install --global prettier
```
> We recommend pinning an exact version of prettier in your `package.json`
> as we introduce stylistic changes in patch releases.
> We recommend pinning an exact version of prettier in your `package.json` as we introduce stylistic changes in patch releases.

View File

@ -3,15 +3,9 @@ id: language-support
title: Language Support
---
Prettier attempts to support all JavaScript language features,
including non-standardized ones. By default it uses the
[Babylon](https://github.com/babel/babylon) parser with all language
features enabled, but you can also use the
[Flow](https://github.com/facebook/flow) parser with the
`parser` API or `--parser` CLI [option](options.md).
Prettier attempts to support all JavaScript language features, including non-standardized ones. By default it uses the [Babylon](https://github.com/babel/babylon) parser with all language features enabled, but you can also use the [Flow](https://github.com/facebook/flow) parser with the `parser` API or `--parser` CLI [option](options.md).
All of JSX and Flow syntax is supported. In fact, the test suite in
`tests/flow` *is* the entire Flow test suite and they all pass.
All of JSX and Flow syntax is supported. In fact, the test suite in `tests/flow` _is_ the entire Flow test suite and they all pass.
Prettier also supports [TypeScript](https://www.typescriptlang.org/), CSS, [Less](http://lesscss.org/), [SCSS](http://sass-lang.com), [JSON](http://json.org/), [GraphQL](http://graphql.org/), and [Markdown](http://commonmark.org).

View File

@ -11,29 +11,29 @@ Specify the line length that the printer will wrap on.
> **For readability we recommend against using more than 80 characters:**
>
>In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don't strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.
> In code styleguides, maximum line length rules are often set to 100 or 120. However, when humans write code, they don't strive to reach the maximum number of columns on every line. Developers often use whitespace to break up long lines for readability. In practice, the average line length often ends up well below the maximum.
>
> Prettier, on the other hand, strives to fit the most code into every line. With the print width set to 120, prettier may produce overly compact, or otherwise undesirable code.
Default | CLI Override | API Override
--------|--------------|-------------
`80` | `--print-width <int>` | `printWidth: <int>`
| Default | CLI Override | API Override |
| ------- | --------------------- | ------------------- |
| `80` | `--print-width <int>` | `printWidth: <int>` |
## Tab Width
Specify the number of spaces per indentation-level.
Default | CLI Override | API Override
--------|--------------|-------------
`2` | `--tab-width <int>` | `tabWidth: <int>`
| Default | CLI Override | API Override |
| ------- | ------------------- | ----------------- |
| `2` | `--tab-width <int>` | `tabWidth: <int>` |
## Tabs
Indent lines with tabs instead of spaces
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--use-tabs` | `useTabs: <bool>`
| Default | CLI Override | API Override |
| ------- | ------------ | ----------------- |
| `false` | `--use-tabs` | `useTabs: <bool>` |
## Semicolons
@ -41,73 +41,76 @@ Print semicolons at the ends of statements.
Valid options:
* `true` - Add a semicolon at the end of every statement.
* `false` - Only add semicolons at the beginning of lines that may introduce ASI failures.
* `true` - Add a semicolon at the end of every statement.
* `false` - Only add semicolons at the beginning of lines that may introduce ASI failures.
Default | CLI Override | API Override
--------|--------------|-------------
`true` | `--no-semi` | `semi: <bool>`
| Default | CLI Override | API Override |
| ------- | ------------ | -------------- |
| `true` | `--no-semi` | `semi: <bool>` |
## Quotes
Use single quotes instead of double quotes.
Notes:
* Quotes in JSX will always be double and ignore this setting.
* If the number of quotes outweighs the other quote, the quote which is less used will be used to format the string - Example: `"I'm double quoted"` results in `"I'm double quoted"` and `"This \"example\" is single quoted"` results in `'This "example" is single quoted'`.
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--single-quote` | `singleQuote: <bool>`
| Default | CLI Override | API Override |
| ------- | ---------------- | --------------------- |
| `false` | `--single-quote` | `singleQuote: <bool>` |
## Trailing Commas
Print trailing commas wherever possible when multi-line. (A single-line array,
for example, never gets trailing commas.)
Print trailing commas wherever possible when multi-line. (A single-line array, for example, never gets trailing commas.)
Valid options:
* `"none"` - No trailing commas.
* `"es5"` - Trailing commas where valid in ES5 (objects, arrays, etc.)
* `"all"` - Trailing commas wherever possible (including function arguments). This requires node 8 or a [transform](https://babeljs.io/docs/plugins/syntax-trailing-function-commas/).
Default | CLI Override | API Override
--------|--------------|-------------
`"none"` | <code>--trailing-comma <none&#124;es5&#124;all></code> | <code>trailingComma: "<none&#124;es5&#124;all>"</code>
* `"none"` - No trailing commas.
* `"es5"` - Trailing commas where valid in ES5 (objects, arrays, etc.)
* `"all"` - Trailing commas wherever possible (including function arguments). This requires node 8 or a [transform](https://babeljs.io/docs/plugins/syntax-trailing-function-commas/).
| Default | CLI Override | API Override |
| -------- | ------------------------------------------------------ | ------------------------------------------------------ |
| `"none"` | <code>--trailing-comma <none&#124;es5&#124;all></code> | <code>trailingComma: "<none&#124;es5&#124;all>"</code> |
## Bracket Spacing
Print spaces between brackets in object literals.
Valid options:
* `true` - Example: `{ foo: bar }`.
* `false` - Example: `{foo: bar}`.
Default | CLI Override | API Override
--------|--------------|-------------
`true` | `--no-bracket-spacing` | `bracketSpacing: <bool>`
* `true` - Example: `{ foo: bar }`.
* `false` - Example: `{foo: bar}`.
| Default | CLI Override | API Override |
| ------- | ---------------------- | ------------------------ |
| `true` | `--no-bracket-spacing` | `bracketSpacing: <bool>` |
## JSX Brackets
Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line (does not apply to self closing elements).
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: <bool>`
| Default | CLI Override | API Override |
| ------- | ------------------------- | ---------------------------- |
| `false` | `--jsx-bracket-same-line` | `jsxBracketSameLine: <bool>` |
## Range
Format only a segment of a file.
These two options can be used to format code starting and ending at a given character offset (inclusive and exclusive, respectively). The range will extend:
* Backwards to the start of the first line containing the selected statement.
* Forwards to the end of the selected statement.
These options cannot be used with `cursorOffset`.
Default | CLI Override | API Override
--------|--------------|-------------
`0` | `--range-start <int>`| `rangeStart: <int>`
`Infinity` | `--range-end <int>` | `rangeEnd: <int>`
| Default | CLI Override | API Override |
| ---------- | --------------------- | ------------------- |
| `0` | `--range-start <int>` | `rangeStart: <int>` |
| `Infinity` | `--range-end <int>` | `rangeEnd: <int>` |
## Parser
@ -116,19 +119,20 @@ Specify which parser to use.
Both the `babylon` and `flow` parsers support the same set of JavaScript features (including Flow). Prettier automatically infers the parser from the input file path, so you shouldn't have to change this setting.
Built-in parsers:
* [`babylon`](https://github.com/babel/babylon/)
* [`flow`](https://github.com/facebook/flow/tree/master/src/parser)
* [`typescript`](https://github.com/eslint/typescript-eslint-parser) _Since v1.4.0_
* [`postcss`](https://github.com/postcss/postcss) _Since v1.4.0_
* [`json`](https://github.com/babel/babylon/tree/f09eb3200f57ea94d51c2a5b1facf2149fb406bf#babylonparseexpressioncode-options) _Since v1.5.0_
* [`graphql`](https://github.com/graphql/graphql-js/tree/master/src/language) _Since v1.5.0_
* [`markdown`](https://github.com/wooorm/remark/tree/master/packages/remark-parse) _Since v1.8.0_
[Custom parsers](api.md#custom-parser-api) are also supported. _Since v1.5.0_
* [`babylon`](https://github.com/babel/babylon/)
* [`flow`](https://github.com/facebook/flow/tree/master/src/parser)
* [`typescript`](https://github.com/eslint/typescript-eslint-parser) _Since v1.4.0_
* [`postcss`](https://github.com/postcss/postcss) _Since v1.4.0_
* [`json`](https://github.com/babel/babylon/tree/f09eb3200f57ea94d51c2a5b1facf2149fb406bf#babylonparseexpressioncode-options) _Since v1.5.0_
* [`graphql`](https://github.com/graphql/graphql-js/tree/master/src/language) _Since v1.5.0_
* [`markdown`](https://github.com/wooorm/remark/tree/master/packages/remark-parse) _Since v1.8.0_
Default | CLI Override | API Override
--------|--------------|-------------
`babylon` | `--parser <string>`<br />`--parser ./my-parser` | `parser: "<string>"`<br />`parser: require("./my-parser")`
[Custom parsers](api.md#custom-parser-api) are also supported. _Since v1.5.0_
| Default | CLI Override | API Override |
| --------- | ----------------------------------------------- | ---------------------------------------------------------- |
| `babylon` | `--parser <string>`<br />`--parser ./my-parser` | `parser: "<string>"`<br />`parser: require("./my-parser")` |
## FilePath
@ -140,16 +144,15 @@ For example, the following will use `postcss` parser:
cat foo | prettier --stdin-filepath foo.css
```
Default | CLI Override | API Override
--------|--------------|-------------
None | `--stdin-filepath <string>` | `filepath: "<string>"`
| Default | CLI Override | API Override |
| ------- | --------------------------- | ---------------------- |
| None | `--stdin-filepath <string>` | `filepath: "<string>"` |
## Require pragma
_available in v1.7.0+_
Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file. This is very useful
when gradually transitioning large, unformatted codebases to prettier.
Prettier can restrict itself to only format files that contain a special comment, called a pragma, at the top of the file. This is very useful when gradually transitioning large, unformatted codebases to prettier.
For example, a file with the following as its first comment will be formatted when `--require-pragma` is supplied:
@ -167,31 +170,26 @@ or
*/
```
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--require-pragma` | `requirePragma: <bool>`
| Default | CLI Override | API Override |
| ------- | ------------------ | ----------------------- |
| `false` | `--require-pragma` | `requirePragma: <bool>` |
## Insert Pragma
_available in v1.8.0+_
Prettier can insert a special @format marker at the top of files specifying that the file has been formatted
with prettier. This works well when used in tandem with the `--require-pragma` option. If there is already a
docblock at the top of the file then this option will add a newline to it with the @format marker.
Prettier can insert a special @format marker at the top of files specifying that the file has been formatted with prettier. This works well when used in tandem with the `--require-pragma` option. If there is already a docblock at the top of the file then this option will add a newline to it with the @format marker.
Default | CLI Override | API Override
--------|--------------|-------------
`false` | `--insert-pragma` | `insertPragma: <bool>`
| Default | CLI Override | API Override |
| ------- | ----------------- | ---------------------- |
| `false` | `--insert-pragma` | `insertPragma: <bool>` |
## Prose Wrap
_available in v1.8.2+_
By default, Prettier will wrap markdown text at the specified print width.
In some cases you may want to rely on editor/viewer soft wrapping instead,
so this option allows you to opt out. When prose wrapping is disabled, each
paragraph will be printed on its own line.
By default, Prettier will wrap markdown text at the specified print width. In some cases you may want to rely on editor/viewer soft wrapping instead, so this option allows you to opt out. When prose wrapping is disabled, each paragraph will be printed on its own line.
Default | CLI Override | API Override
--------|--------------|-------------
`true` | `--no-prose-wrap` | `proseWrap: <bool>`
| Default | CLI Override | API Override |
| ------- | ----------------- | ------------------- |
| `true` | `--no-prose-wrap` | `proseWrap: <bool>` |

View File

@ -21,29 +21,24 @@ and add this config to your `package.json`:
"precommit": "lint-staged"
},
"lint-staged": {
"*.{js,json,css}": [
"prettier --write",
"git add"
]
"*.{js,json,css}": ["prettier --write", "git add"]
}
}
```
There is a limitation where if you stage specific lines this approach will stage the whole file after regardless. See this [issue](https://github.com/okonet/lint-staged/issues/62) for more info.
See https://github.com/okonet/lint-staged#configuration for more details about how you can configure lint-staged.
## Option 2. [pre-commit](https://github.com/pre-commit/pre-commit)
Copy the following config into your `.pre-commit-config.yaml` file:
```yaml
- repo: https://github.com/prettier/prettier
sha: '' # Use the sha or tag you want to point at
hooks:
- id: prettier
```
Find more info from [here](http://pre-commit.com).

View File

@ -5,7 +5,6 @@ title: Rationale
Prettier is an opinionated code formatter. This document gives a rationale behind those opinions.
## What prettier is concerned about
### Consistency
@ -16,7 +15,6 @@ Prettier exists for one purpose: to enforce consistency across your entire proje
The first requirement of prettier is to output valid JavaScript and code that has the exact same behavior as before formatting. Please report any JavaScript code where prettier fails to follow these correctness rules — that's a bug which needs to be fixed!
### Whitespace: indentation and line breaks
This is the core of prettier. The formatting rules are going to be explained in a later section.
@ -25,40 +23,36 @@ This is the core of prettier. The formatting rules are going to be explained in
Prettier enforces double quotes by default, but has a setting for enforcing single quotes instead. There are two exceptions:
- The number of escaped quotes are minimized. For example, if you have a string with a single quote inside, it will be enclosed in double quotes regardless of the quote setting: `"that's a double quote"`, not `'that\'s a double quote'`.
- JSX always uses double quotes. JSX takes its roots from HTML, where the dominant use of quotes for attributes is double quotes. Browser developer tools also follow this convention by always displaying HTML with double quotes, even if the source code uses single quotes.
* The number of escaped quotes are minimized. For example, if you have a string with a single quote inside, it will be enclosed in double quotes regardless of the quote setting: `"that's a double quote"`, not `'that\'s a double quote'`.
* JSX always uses double quotes. JSX takes its roots from HTML, where the dominant use of quotes for attributes is double quotes. Browser developer tools also follow this convention by always displaying HTML with double quotes, even if the source code uses single quotes.
Prettier maintains the way your string is escaped. For example, `"🙂"` won't be formatted into `"\uD83D\uDE42"` and vice versa.
### Parentheses
Prettier outputs the minimum number of parentheses required to ensure that the behavior of the formatted code stays unchanged. This may lead to code that feels ambiguous. If that's the case, you are encouraged to extract the ambiguous parts into variables.
### Empty lines
It turns out that empty lines are very hard to automatically generate. The approach that prettier takes is to preserve empty lines the way they were in the original source code. The only constraint is that prettier disallows several empty lines in a row. They are collapsed to a single one.
### Multi-line objects
It is tempting to collapse an object to a single line if it fits, but there are times when it is better for sibling/cousin keys to stay vertically aligned—see [object lists], [nested configs], [stylesheets], and [keyed methods]. To avoid unfavorable collapsing, prettier simply formats any object as multi-line if it appears as such in the original source code. This is the same strategy used by [elm-format] for multi-line records.
[object lists]:https://github.com/prettier/prettier/issues/74#issue-199965534
[nested configs]:https://github.com/prettier/prettier/issues/88#issuecomment-275448346
[stylesheets]:https://github.com/prettier/prettier/issues/74#issuecomment-275262094
[keyed methods]:https://github.com/prettier/prettier/pull/495#issuecomment-275745434
[elm-format]:https://github.com/prettier/prettier/issues/74#issuecomment-275621526
[object lists]: https://github.com/prettier/prettier/issues/74#issue-199965534
[nested configs]: https://github.com/prettier/prettier/issues/88#issuecomment-275448346
[stylesheets]: https://github.com/prettier/prettier/issues/74#issuecomment-275262094
[keyed methods]: https://github.com/prettier/prettier/pull/495#issuecomment-275745434
[elm-format]: https://github.com/prettier/prettier/issues/74#issuecomment-275621526
## What prettier is _not_ concerned about
Here are a few examples of things that are out of scope for prettier:
- Turning single/double quotes into template literals or vice versa.
- Adding/removing `{}` and `return` where they are optional.
- Turning `?:` into `if then else`.
* Turning single/double quotes into template literals or vice versa.
* Adding/removing `{}` and `return` where they are optional.
* Turning `?:` into `if then else`.
<!--
### Semi-colons

View File

@ -5,38 +5,32 @@ title: Related Projects
## ESLint Integrations
- [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier) plugs Prettier into your ESLint workflow
- [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) turns off all ESLint rules that are unnecessary or might conflict with Prettier
- [`prettier-eslint`](https://github.com/prettier/prettier-eslint)
passes `prettier` output to `eslint --fix`
- [`prettier-standard`](https://github.com/sheerun/prettier-standard)
uses `prettier` and `prettier-eslint` to format code with standard rules
- [`prettier-standard-formatter`](https://github.com/dtinth/prettier-standard-formatter)
passes `prettier` output to `standard --fix`
* [`eslint-plugin-prettier`](https://github.com/prettier/eslint-plugin-prettier) plugs Prettier into your ESLint workflow
* [`eslint-config-prettier`](https://github.com/prettier/eslint-config-prettier) turns off all ESLint rules that are unnecessary or might conflict with Prettier
* [`prettier-eslint`](https://github.com/prettier/prettier-eslint) passes `prettier` output to `eslint --fix`
* [`prettier-standard`](https://github.com/sheerun/prettier-standard) uses `prettier` and `prettier-eslint` to format code with standard rules
* [`prettier-standard-formatter`](https://github.com/dtinth/prettier-standard-formatter) passes `prettier` output to `standard --fix`
## TSLint Integrations
- [`tslint-plugin-prettier`](https://github.com/ikatyang/tslint-plugin-prettier) runs Prettier as a TSLint rule and reports differences as individual TSLint issues
- [`tslint-config-prettier`](https://github.com/alexjoverm/tslint-config-prettier) use TSLint with Prettier without any conflict
- [`prettier-tslint`](https://github.com/azz/prettier-tslint)
passes `prettier` output to `tslint --fix`
* [`tslint-plugin-prettier`](https://github.com/ikatyang/tslint-plugin-prettier) runs Prettier as a TSLint rule and reports differences as individual TSLint issues
* [`tslint-config-prettier`](https://github.com/alexjoverm/tslint-config-prettier) use TSLint with Prettier without any conflict
* [`prettier-tslint`](https://github.com/azz/prettier-tslint) passes `prettier` output to `tslint --fix`
## stylelint Integrations
- [`prettier-stylelint`](https://github.com/hugomrdias/prettier-stylelint)
passes `prettier` output to `stylelint --fix`
- [`stylelint-config-prettier`](https://github.com/shannonmoeller/stylelint-config-prettier) turns off all rules that are unnecessary or might conflict with Prettier.
* [`prettier-stylelint`](https://github.com/hugomrdias/prettier-stylelint) passes `prettier` output to `stylelint --fix`
* [`stylelint-config-prettier`](https://github.com/shannonmoeller/stylelint-config-prettier) turns off all rules that are unnecessary or might conflict with Prettier.
## Forks
- [`prettier-miscellaneous`](https://github.com/arijs/prettier-miscellaneous)
`prettier` with a few minor extra options
* [`prettier-miscellaneous`](https://github.com/arijs/prettier-miscellaneous) `prettier` with a few minor extra options
## Misc
- [`neutrino-preset-prettier`](https://github.com/SpencerCDixon/neutrino-preset-prettier) allows you to use Prettier as a Neutrino preset
- [`prettier_d`](https://github.com/josephfrazier/prettier_d.js) runs Prettier as a server to avoid Node.js startup delay. It also supports configuration via `.prettierrc`, `package.json`, and `.editorconfig`.
- [`Prettier Bookmarklet`](https://prettier.glitch.me/) provides a bookmarklet and exposes a REST API for Prettier that allows to format CodeMirror editor in your browser
- [`prettier-github`](https://github.com/jgierer12/prettier-github) formats code in GitHub comments
- [`rollup-plugin-prettier`](https://github.com/mjeanroy/rollup-plugin-prettier) allows you to use Prettier with Rollup
- [`markdown-magic-prettier`](https://github.com/camacho/markdown-magic-prettier) allows you to use Prettier to format JS [codeblocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/) in Markdown files via [Markdown Magic](https://github.com/DavidWells/markdown-magic)
* [`neutrino-preset-prettier`](https://github.com/SpencerCDixon/neutrino-preset-prettier) allows you to use Prettier as a Neutrino preset
* [`prettier_d`](https://github.com/josephfrazier/prettier_d.js) runs Prettier as a server to avoid Node.js startup delay. It also supports configuration via `.prettierrc`, `package.json`, and `.editorconfig`.
* [`Prettier Bookmarklet`](https://prettier.glitch.me/) provides a bookmarklet and exposes a REST API for Prettier that allows to format CodeMirror editor in your browser
* [`prettier-github`](https://github.com/jgierer12/prettier-github) formats code in GitHub comments
* [`rollup-plugin-prettier`](https://github.com/mjeanroy/rollup-plugin-prettier) allows you to use Prettier with Rollup
* [`markdown-magic-prettier`](https://github.com/camacho/markdown-magic-prettier) allows you to use Prettier to format JS [codeblocks](https://help.github.com/articles/creating-and-highlighting-code-blocks/) in Markdown files via [Markdown Magic](https://github.com/DavidWells/markdown-magic)

View File

@ -3,25 +3,10 @@ id: technical-details
title: Technical Details
---
This printer is a fork of
[recast](https://github.com/benjamn/recast)'s printer with its
algorithm replaced by the one described by Wadler in "[A prettier
printer](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf)".
There still may be leftover code from recast that needs to be cleaned
up.
This printer is a fork of [recast](https://github.com/benjamn/recast)'s printer with its algorithm replaced by the one described by Wadler in "[A prettier printer](http://homepages.inf.ed.ac.uk/wadler/papers/prettier/prettier.pdf)". There still may be leftover code from recast that needs to be cleaned up.
The basic idea is that the printer takes an AST and returns an
intermediate representation of the output, and the printer uses that
to generate a string. The advantage is that the printer can "measure"
the IR and see if the output is going to fit on a line, and break if
not.
The basic idea is that the printer takes an AST and returns an intermediate representation of the output, and the printer uses that to generate a string. The advantage is that the printer can "measure" the IR and see if the output is going to fit on a line, and break if not.
This means that most of the logic of printing an AST involves
generating an abstract representation of the output involving certain
commands. For example, `concat(["(", line, arg, line ")"])` would
represent a concatenation of opening parens, an argument, and closing
parens. But if that doesn't fit on one line, the printer can break
where `line` is specified.
This means that most of the logic of printing an AST involves generating an abstract representation of the output involving certain commands. For example, `concat(["(", line, arg, line ")"])` would represent a concatenation of opening parens, an argument, and closing parens. But if that doesn't fit on one line, the printer can break where `line` is specified.
More (rough) details can be found in
[commands.md](https://github.com/prettier/prettier/commands.md).
More (rough) details can be found in [commands.md](https://github.com/prettier/prettier/commands.md).

View File

@ -5,7 +5,7 @@ title: Vim Setup
Vim users can simply install either [sbdchd](https://github.com/sbdchd)/[neoformat](https://github.com/sbdchd/neoformat), [w0rp](https://github.com/w0rp)/[ale](https://github.com/w0rp/ale), or [prettier](https://github.com/prettier)/[vim-prettier](https://github.com/prettier/vim-prettier).
--------------------------------------------------------------------------------
---
## Neoformat
@ -52,7 +52,7 @@ let g:neoformat_try_formatprg = 1
Each space in prettier options should be escaped with `\`.
--------------------------------------------------------------------------------
---
## vim-prettier
@ -88,7 +88,9 @@ Prettier by default will run on auto save but can also be manually triggered by:
```
<Leader>p
```
or
```
:Prettier
```
@ -119,8 +121,7 @@ By default parsing errors will open the quickfix but can also be disabled
let g:prettier#quickfix_enabled = 0
```
To enable vim-prettier to run in files without requiring the "@format" doc tag.
First disable the default autoformat, then update to your own custom behaviour
To enable vim-prettier to run in files without requiring the "@format" doc tag. First disable the default autoformat, then update to your own custom behaviour
Running before saving sync:
@ -175,21 +176,17 @@ g:prettier#config#trailing_comma = 'all'
" flow|babylon|typescript|postcss
g:prettier#config#parser = 'flow'
```
--------------------------------------------------------------------------------
---
## ALE
### ALE - Installation
[ALE](https://github.com/w0rp/ale) is an asynchronous lint engine for Vim that
also has the ability to run formatters over code, including Prettier. For ALE
to work you'll have to be using either Vim 8 or Neovim as ALE makes use of the
asynchronous abilities that both Vim 8 and Neovim provide.
[ALE](https://github.com/w0rp/ale) is an asynchronous lint engine for Vim that also has the ability to run formatters over code, including Prettier. For ALE to work you'll have to be using either Vim 8 or Neovim as ALE makes use of the asynchronous abilities that both Vim 8 and Neovim provide.
The best way to install ALE is with your favourite plugin manager for Vim, such
as [Vim-Plug](https://github.com/junegunn/vim-plug):
The best way to install ALE is with your favourite plugin manager for Vim, such as [Vim-Plug](https://github.com/junegunn/vim-plug):
```
Plug 'w0rp/ale'
@ -206,43 +203,37 @@ let g:ale_fixers = {}
let g:ale_fixers['javascript'] = ['prettier']
```
ALE will first use the Prettier installed locally (in
`node_modules/.bin/prettier`) before looking for a global installation.
ALE will first use the Prettier installed locally (in `node_modules/.bin/prettier`) before looking for a global installation.
You can then run `:ALEFix` in a JavaScript file to run Prettier.
### ALE - Configuration
To have ALE run `prettier` when you save a file you can tell ALE to run
automatically:
To have ALE run `prettier` when you save a file you can tell ALE to run automatically:
```
let g:ale_fix_on_save = 1
```
To configure Prettier, you can set `g:ale_javascript_prettier_options`. This is
a string that will be passed through to the Prettier command line tool:
To configure Prettier, you can set `g:ale_javascript_prettier_options`. This is a string that will be passed through to the Prettier command line tool:
```
let g:ale_javascript_prettier_options = '--single-quote --trailing-comma es5'
```
If you use Prettier config files, you must set
`g:ale_javascript_prettier_use_local_config` to have ALE respect them:
If you use Prettier config files, you must set `g:ale_javascript_prettier_use_local_config` to have ALE respect them:
```
let g:ale_javascript_prettier_use_local_config = 1
```
--------------------------------------------------------------------------------
---
## Running manually
### Running Prettier manually in Vim
If you need a little more control over when prettier is run, you can create a
custom key binding. In this example, `gp` (mnemonic: "get pretty") is used to
run prettier (with options) in the currently active buffer:
If you need a little more control over when prettier is run, you can create a custom key binding. In this example, `gp` (mnemonic: "get pretty") is used to run prettier (with options) in the currently active buffer:
```
nnoremap gp :silent %!prettier --stdin --trailing-comma all --single-quote<CR>

View File

@ -7,7 +7,7 @@ title: Webstorm Setup
https://blog.jetbrains.com/webstorm/2016/08/using-external-tools/
Go to *File | Settings | Tools | External Tools* for Windows and Linux or *WebStorm | Preferences | Tools | External Tools* for OS X and click **+** to add a new tool. Lets name it **Prettier**.
Go to _File | Settings | Tools | External Tools_ for Windows and Linux or _WebStorm | Preferences | Tools | External Tools_ for OS X and click **+** to add a new tool. Lets name it **Prettier**.
* **Program** set `prettier`
@ -30,7 +30,7 @@ Go to *File | Settings | Tools | External Tools* for Windows and Linux or *WebSt
### Configure Keymap
Now when you setup **External Tool** I guess you want to add hotkey for it. Go to *File | Settings | Keymap* for Windows and Linux *WebStorm | Preferences | Keymap* and type external tool name in search box.
Now when you setup **External Tool** I guess you want to add hotkey for it. Go to _File | Settings | Keymap_ for Windows and Linux _WebStorm | Preferences | Keymap_ and type external tool name in search box.
See [this documentation](https://www.jetbrains.com/help/webstorm/configuring-keyboard-shortcuts.html) about configuring keyboard shortcuts.
@ -38,7 +38,7 @@ See [this documentation](https://www.jetbrains.com/help/webstorm/configuring-key
To automatically format using `prettier` on save, you can use a file watcher.
Go to *File | Settings | Tools | File Watchers* for Windows and Linux or *WebStorm | Preferences | Tools | File Watchers* for OS X and click **+** to add a new tool. Lets name it **Prettier**.
Go to _File | Settings | Tools | File Watchers_ for Windows and Linux or _WebStorm | Preferences | Tools | File Watchers_ for OS X and click **+** to add a new tool. Lets name it **Prettier**.
* **File Type**: JavaScript
* **Scope**: Current File

View File

@ -7,54 +7,53 @@ title: Why Prettier?
By far the biggest reason for adopting Prettier is to stop all the on-going debates over styles. It is generally accepted that having a common style guide is valuable for a project and team but getting there is a very painful and unrewarding process. People get very emotional around particular ways of writing code and nobody likes spending time writing and receiving nits.
- “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.”
- “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going "great debate" that wasted lots of little back and forth bits. It's far easier for us all to agree now: just run Prettier, and go with that style.”
- “Getting tired telling people how to style their product code.”
- “Our top reason was to stop wasting our time debating style nits.”
- “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.”
- “I don't want anybody to nitpick any other person ever again.”
- “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn't want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.”
* “We want to free mental threads and end discussions around style. While sometimes fruitful, these discussions are for the most part wasteful.”
* “Literally had an engineer go through a huge effort of cleaning up all of our code because we were debating ternary style for the longest time and were inconsistent about it. It was dumb, but it was a weird on-going "great debate" that wasted lots of little back and forth bits. It's far easier for us all to agree now: just run Prettier, and go with that style.”
* “Getting tired telling people how to style their product code.”
* “Our top reason was to stop wasting our time debating style nits.”
* “Having a githook set up has reduced the amount of style issues in PRs that result in broken builds due to ESLint rules or things I have to nit-pick or clean up later.”
* “I don't want anybody to nitpick any other person ever again.”
* “It reminds me of how Steve Jobs used to wear the same clothes every day because he has a million decisions to make and he didn't want to be bothered to make trivial ones like picking out clothes. I think Prettier is like that.”
## Helping Newcomers
Prettier is usually introduced by people with experience in the current codebase and JavaScript but the people that disproportionally benefit from it are newcomers to the codebase. One may think that it's only useful for people with very limited programming experience, but we've seen it quicken the ramp up time from experienced engineers joining the company, as they likely used a different coding style before, and developers coming from a different programming language.
- “My motivations for using Prettier are: appearing that I know how to write JavaScript well.”
- “I always put spaces in the wrong place, now I don't have to worry about it anymore.”
- “When you're a beginner you're making a lot of mistakes caused by the syntax. Thanks to Prettier, you can reduce these mistakes and save a lot of time to focus on what really matters.”
- “As a teacher, I will also tell to my students to install Prettier to help them to learn the JS syntax and have readable files.”
* “My motivations for using Prettier are: appearing that I know how to write JavaScript well.”
* “I always put spaces in the wrong place, now I don't have to worry about it anymore.”
* “When you're a beginner you're making a lot of mistakes caused by the syntax. Thanks to Prettier, you can reduce these mistakes and save a lot of time to focus on what really matters.”
* “As a teacher, I will also tell to my students to install Prettier to help them to learn the JS syntax and have readable files.”
## Writing code
What usually happens once people are using Prettier is that they realize that they actually spend a lot of time and mental energy formatting their code. With Prettier editor integration, you can just press that magic key binding and poof, the code is formatted. This is an eye opening experience if anything else.
- “I want to write code. Not spend cycles on formatting.”
- “It removed 5% that sucks in our daily life - aka formatting”
- “We're in 2017 and it's still painful to break a call into multiple lines when you happen to add an argument that makes it go over the 80 columns limit :(“
* “I want to write code. Not spend cycles on formatting.”
* “It removed 5% that sucks in our daily life - aka formatting”
* “We're in 2017 and it's still painful to break a call into multiple lines when you happen to add an argument that makes it go over the 80 columns limit :(“
## Easy to adopt
We've worked very hard to use the least controversial coding styles, went through many rounds of fixing all the edge cases and polished the getting started experience. When you're ready to push Prettier into your codebase, not only should it be painless for you to do it technically but the newly formatted codebase should not generate major controversy and be accepted painlessly by your co-workers.
- “It's low overhead. We were able to throw Prettier at very different kinds of repos without much work.”
- “It's been mostly bug free. Had there been major styling issues during the course of implementation we would have been wary about throwing this at our JS codebase. I'm happy to say that's not the case.”
- “Everyone runs it as part of their pre commit scripts, a couple of us use the editor on save extensions as well.”
- “It's fast, against one of our larger JS codebases we were able to run Prettier in under 13 seconds.”
- “The biggest benefit for Prettier for us was being able to format the entire code base at once.”
* “It's low overhead. We were able to throw Prettier at very different kinds of repos without much work.”
* “It's been mostly bug free. Had there been major styling issues during the course of implementation we would have been wary about throwing this at our JS codebase. I'm happy to say that's not the case.”
* “Everyone runs it as part of their pre commit scripts, a couple of us use the editor on save extensions as well.”
* “It's fast, against one of our larger JS codebases we were able to run Prettier in under 13 seconds.”
* “The biggest benefit for Prettier for us was being able to format the entire code base at once.”
## Clean up an existing codebase
Since coming up with a coding style and enforcing it is a big undertaking, it often slips through the cracks and you are left working on inconsistent codebases. Running Prettier in this case is a quick win, the codebase is now uniform and easier to read without spending hardly any time.
- “Take a look at the code :) I just need to restore sanity.”
- “We inherited a ~2000 module ES6 code base, developed by 20 different developers over 18 months, in a global team. Felt like such a win without much research.”
* “Take a look at the code :) I just need to restore sanity.”
* “We inherited a ~2000 module ES6 code base, developed by 20 different developers over 18 months, in a global team. Felt like such a win without much research.”
## Ride the hype train
Purely technical aspects of the projects aren't the only thing people look into when choosing to adopt Prettier. Who built and uses it and how quickly it spreads through the community has a non-trivial impact.
- “The amazing thing, for me, is: 1) Announced 2 months ago. 2) Already adopted by, it seems, every major JS project. 3) 7000 stars, 100,000 npm downloads/mo”
- “Was built by the same people as React & React Native.”
- “I like to be part of the hot new things.”
- “Because soon enough people are gonna ask for it.”
* “The amazing thing, for me, is: 1) Announced 2 months ago. 2) Already adopted by, it seems, every major JS project. 3) 7000 stars, 100,000 npm downloads/mo”
* “Was built by the same people as React & React Native.”
* “I like to be part of the hot new things.”
* “Because soon enough people are gonna ask for it.”

View File

@ -11,7 +11,6 @@ const printDocToDebug = require("./src/doc-debug").printDocToDebug;
const config = require("./src/resolve-config");
const getSupportInfo = require("./src/support").getSupportInfo;
const docblock = require("jest-docblock");
const getStream = require("get-stream");
function guessLineEnding(text) {
const index = text.indexOf("\n");
@ -395,7 +394,6 @@ module.exports = {
/* istanbul ignore next */
__debug: {
getStream,
parse: function(text, opts) {
return parser.parse(text, opts);
},

View File

@ -63,7 +63,8 @@
"eslint-plugin-react": "7.1.0",
"jest": "21.1.0",
"mkdirp": "0.5.1",
"prettier": "1.8.0",
"prettier": "1.8.2",
"prettylint": "1.0.0",
"rimraf": "2.6.2",
"rollup": "0.41.6",
"rollup-plugin-commonjs": "7.0.2",
@ -85,6 +86,7 @@
"test:dist": "cross-env NODE_ENV=production yarn test",
"test-integration": "jest tests_integration",
"lint": "cross-env EFF_NO_LINK_RULES=true eslint . --format node_modules/eslint-friendly-formatter",
"lint-docs": "prettylint {.,docs,website}/*.md",
"build": "node ./scripts/build/build.js",
"check-deps": "node ./scripts/check-deps.js"
}

View File

@ -40,6 +40,9 @@ shell.echo("Bundling lib bin...");
shell.exec("rollup -c scripts/build/rollup.bin.config.js");
shell.chmod("+x", "./dist/bin/prettier.js");
shell.echo("Bundling lib third-party...");
shell.exec("rollup -c scripts/build/rollup.third-party.config.js");
for (const parser of parsers) {
if (parser === "postcss") {
continue;
@ -66,9 +69,13 @@ shell.echo();
// --- Docs ---
shell.echo("Bundling docs index...");
shell.cp("dist/index.js", `${docs}/index.js`);
shell.exec(
`node_modules/babel-cli/bin/babel.js dist/index.js --out-file ${
`rollup -c scripts/build/rollup.index.config.js --environment BUILD_TARGET:website -o ${
docs
}/index.js`
);
shell.exec(
`node_modules/babel-cli/bin/babel.js ${docs}/index.js --out-file ${
docs
}/index.js --presets=es2015`
);

View File

@ -3,6 +3,7 @@ import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import json from "rollup-plugin-json";
import replace from "rollup-plugin-replace";
import * as path from "path";
export default Object.assign(baseConfig, {
entry: "bin/prettier.js",
@ -10,19 +11,22 @@ export default Object.assign(baseConfig, {
format: "cjs",
banner: "#!/usr/bin/env node",
plugins: [
replace({
"#!/usr/bin/env node": "",
// The require-from-string module (a dependency of cosmiconfig) assumes
// that `module.parent` exists, but it only does for `require`:ed modules.
// Usually, require-from-string is _always_ `require`:ed, but when bundled
// with rollup the module is turned into a plain function located directly
// in bin/prettier.js so `module.parent` does not exist. Defaulting to
// `module` instead seems to work.
"module.parent": "(module.parent || module)"
}),
replace({ "#!/usr/bin/env node": "" }),
json(),
resolve({ preferBuiltins: true }),
commonjs()
],
external: ["fs", "readline", "path", "module", "assert", "util", "events"]
external: [
"fs",
"readline",
"path",
"module",
"assert",
"util",
"events",
path.resolve("src/third-party.js")
],
paths: {
[path.resolve("src/third-party.js")]: "../third-party"
}
});

View File

@ -3,6 +3,13 @@ import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import json from "rollup-plugin-json";
import replace from "rollup-plugin-replace";
import * as path from "path";
const external = ["assert"];
if (process.env.BUILD_TARGET !== "website") {
external.push(path.resolve("src/third-party.js"));
}
export default Object.assign(baseConfig, {
entry: "index.js",
@ -10,18 +17,14 @@ export default Object.assign(baseConfig, {
format: "cjs",
plugins: [
replace({
// The require-from-string module (a dependency of cosmiconfig) assumes
// that `module.parent` exists, but it only does for `require`:ed modules.
// Usually, require-from-string is _always_ `require`:ed, but when bundled
// with rollup the module is turned into a plain function located directly
// in index.js so `module.parent` does not exist. Defaulting to `module`
// instead seems to work.
"module.parent": "(module.parent || module)",
"process.env.NODE_ENV": JSON.stringify("production")
}),
json(),
resolve({ preferBuiltins: true }),
commonjs()
],
external: ["assert"]
external,
paths: {
[path.resolve("src/third-party.js")]: "./third-party"
}
});

View File

@ -0,0 +1,26 @@
import baseConfig from "./rollup.base.config.js";
import resolve from "rollup-plugin-node-resolve";
import commonjs from "rollup-plugin-commonjs";
import json from "rollup-plugin-json";
import replace from "rollup-plugin-replace";
export default Object.assign(baseConfig, {
entry: "src/third-party.js",
dest: "dist/third-party.js",
format: "cjs",
plugins: [
replace({
// The require-from-string module (a dependency of cosmiconfig) assumes
// that `module.parent` exists, but it only does for `require`:ed modules.
// Usually, require-from-string is _always_ `require`:ed, but when bundled
// with rollup the module is turned into a plain function located directly
// in index.js so `module.parent` does not exist. Defaulting to `module`
// instead seems to work.
"module.parent": "(module.parent || module)"
}),
json(),
resolve({ preferBuiltins: true }),
commonjs()
],
external: ["assert"]
});

View File

@ -19,6 +19,7 @@ const validator = require("./cli-validator");
const apiDefaultOptions = require("./options").defaults;
const errors = require("./errors");
const logger = require("./cli-logger");
const thirdParty = require("./third-party");
const OPTION_USAGE_THRESHOLD = 25;
const CHOICE_USAGE_MARGIN = 3;
@ -225,7 +226,7 @@ function applyConfigPrecedence(argv, options) {
}
function formatStdin(argv) {
prettier.__debug.getStream(process.stdin).then(input => {
thirdParty.getStream(process.stdin).then(input => {
const filepath = argv["stdin-filepath"]
? path.resolve(process.cwd(), argv["stdin-filepath"])
: process.cwd();

View File

@ -1,12 +1,12 @@
"use strict";
const cosmiconfig = require("cosmiconfig");
const thirdParty = require("./third-party");
const minimatch = require("minimatch");
const path = require("path");
const mem = require("mem");
const getExplorerMemoized = mem(opts =>
cosmiconfig("prettier", {
thirdParty.cosmiconfig("prettier", {
sync: opts.sync,
cache: opts.cache,
rcExtensions: true,

9
src/third-party.js Normal file
View File

@ -0,0 +1,9 @@
"use strict";
const getStream = require("get-stream");
const cosmiconfig = require("cosmiconfig");
module.exports = {
getStream,
cosmiconfig
};

View File

@ -6,8 +6,8 @@ const stripAnsi = require("strip-ansi");
const ENV_LOG_LEVEL = require("../src/cli-logger").ENV_LOG_LEVEL;
const isProduction = process.env.NODE_ENV === "production";
const prettierApi = isProduction ? "../dist/index" : "../index";
const prettierCli = isProduction ? "../dist/bin/prettier" : "../bin/prettier";
const thirdParty = isProduction ? "../dist/third-party" : "../src/third-party";
function runPrettier(dir, args, options) {
args = args || [];
@ -68,11 +68,17 @@ function runPrettier(dir, args, options) {
// We cannot use `jest.setMock("get-stream", impl)` here, because in the
// production build everything is bundled into one file so there is no
// "get-stream" module to mock.
jest.spyOn(require(thirdParty), "getStream").mockImplementation(() => ({
then: handler => handler(options.input || "")
}));
jest
.spyOn(require(prettierApi).__debug, "getStream")
.mockImplementation(() => ({
then: handler => handler(options.input || "")
}));
.spyOn(require(thirdParty), "cosmiconfig")
.mockImplementation((moduleName, options) =>
require("cosmiconfig")(
moduleName,
Object.assign({}, options, { stopDir: __dirname })
)
);
try {
require(prettierCli);

View File

@ -1,10 +1,11 @@
## Configuration
In the project repo, the `docs` folder is used to hold documentation written in markdown. A `blog` folder can be used to hold blog posts written in markdown.
### Document and Blog Front Matters
Documentation should contain front matter that follows this example:
```
---
id: doc1 <!-- used for docs to find each other and to map links -->
@ -19,6 +20,7 @@ next: doc2 <!-- next doc on the sidebar for navigation -->
```
Blog posts should be written as markdown files with the following front matter:
```
---
title: Blog Post Title
@ -27,6 +29,7 @@ authorURL: http://twitter.com/author <!-- (or some other link) -->
authorFBID: 21315325 <!-- id to get author's picture -->
---
```
In the blog post you should include a line `<!--truncate-->`. This will determine under which point text will be ignored when generating the preview of your blog post. Blog posts should have the file name format: `yyyy-mm-dd-your-file-name.md`.
### Language Configurations
@ -57,7 +60,6 @@ yarn start
This will start a server hosting your website locally at `localhost:3000`. This server will ignore any occurrences `siteConfig.baseUrl` in URLs, e.g. `localhost:3000/your-site/index.html` will be the same as `localhost:3000/index.html`. Any changes to configured files will be reflected by refreshing the page, i.e. the server does not need to be restarted to show changes.
### Build Static Pages
To create a static build of your website, run the script:

154
yarn.lock
View File

@ -147,6 +147,10 @@ array-equal@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/array-equal/-/array-equal-1.0.0.tgz#8c2a5ef2472fd9ea742b04c77a75093ba2757c93"
array-find-index@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/array-find-index/-/array-find-index-1.0.2.tgz#df010aa1287e164bbda6f9723b0a96a1ec4187a1"
array-union@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/array-union/-/array-union-1.0.2.tgz#9a34410e4f4e3da23dea375be5be70f24778ec39"
@ -953,6 +957,13 @@ callsites@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/callsites/-/callsites-2.0.0.tgz#06eb84f00eea413da86affefacbffb36093b3c50"
camelcase-keys@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-2.1.0.tgz#308beeaffdf28119051efa1d932213c91b8f92e7"
dependencies:
camelcase "^2.0.0"
map-obj "^1.0.0"
camelcase@4.1.0, camelcase@^4.1.0:
version "4.1.0"
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-4.1.0.tgz#d545635be1e33c542649c69173e5de6acfae34dd"
@ -961,6 +972,10 @@ camelcase@^1.0.2:
version "1.2.1"
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-1.2.1.tgz#9bb5304d2e0b56698b2c758b08a3eaa9daa58a39"
camelcase@^2.0.0:
version "2.1.1"
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-2.1.1.tgz#7c1d16d679a1bbe59ca02cacecfb011e201f5a1f"
camelcase@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a"
@ -998,7 +1013,7 @@ chalk@^1.0.0, chalk@^1.1.0, chalk@^1.1.1, chalk@^1.1.3:
strip-ansi "^3.0.0"
supports-color "^2.0.0"
chalk@^2.3.0:
chalk@^2.1.0, chalk@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.3.0.tgz#b5ea48efc9c1793dccc9b4767c93914d3f2d52ba"
dependencies:
@ -1259,6 +1274,12 @@ cssom@0.3.x, "cssom@>= 0.3.2 < 0.4.0":
dependencies:
cssom "0.3.x"
currently-unhandled@^0.4.1:
version "0.4.1"
resolved "https://registry.yarnpkg.com/currently-unhandled/-/currently-unhandled-0.4.1.tgz#988df33feab191ef799a61369dd76c17adf957ea"
dependencies:
array-find-index "^1.0.1"
dashdash@^1.12.0:
version "1.14.1"
resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0"
@ -1279,7 +1300,7 @@ debug@^2.1.1, debug@^2.2.0, debug@^2.6.3, debug@^2.6.8:
dependencies:
ms "2.0.0"
decamelize@^1.0.0, decamelize@^1.1.1:
decamelize@^1.0.0, decamelize@^1.1.1, decamelize@^1.1.2:
version "1.2.0"
resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290"
@ -1426,6 +1447,16 @@ escodegen@^1.6.1:
optionalDependencies:
source-map "~0.2.0"
eslint-formatter-pretty@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/eslint-formatter-pretty/-/eslint-formatter-pretty-1.3.0.tgz#985d9e41c1f8475f4a090c5dbd2dfcf2821d607e"
dependencies:
ansi-escapes "^2.0.0"
chalk "^2.1.0"
log-symbols "^2.0.0"
plur "^2.1.2"
string-width "^2.0.0"
eslint-friendly-formatter@3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/eslint-friendly-formatter/-/eslint-friendly-formatter-3.0.0.tgz#278874435a6c46ec1d94fa0b1ff494e30ef04290"
@ -1472,6 +1503,13 @@ eslint-plugin-prettier@2.1.2:
fast-diff "^1.1.1"
jest-docblock "^20.0.1"
eslint-plugin-prettier@^2.2.0:
version "2.3.1"
resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-2.3.1.tgz#e7a746c67e716f335274b88295a9ead9f544e44d"
dependencies:
fast-diff "^1.1.1"
jest-docblock "^21.0.0"
eslint-plugin-react@7.1.0:
version "7.1.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-react/-/eslint-plugin-react-7.1.0.tgz#27770acf39f5fd49cd0af4083ce58104eb390d4c"
@ -1823,6 +1861,10 @@ get-caller-file@^1.0.1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5"
get-stdin@^4.0.1:
version "4.0.1"
resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-4.0.1.tgz#b968c6b0a04384324902e8bf1a5df32579a450fe"
get-stream@3.0.0, get-stream@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-3.0.0.tgz#8e943d1358dc37555054ecbe2edb05aa174ede14"
@ -1861,7 +1903,7 @@ globals@^9.0.0, globals@^9.17.0, globals@^9.18.0:
version "9.18.0"
resolved "https://registry.yarnpkg.com/globals/-/globals-9.18.0.tgz#aa3896b3e69b487f17e31ed2143d69a8e30c2d8a"
globby@6.1.0:
globby@6.1.0, globby@^6.1.0:
version "6.1.0"
resolved "https://registry.yarnpkg.com/globby/-/globby-6.1.0.tgz#f5a6d70e8395e21c858fb0489d64df02424d506c"
dependencies:
@ -2028,7 +2070,7 @@ ieee754@^1.1.4:
version "1.1.8"
resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.1.8.tgz#be33d40ac10ef1926701f6f08a2d86fbfd1ad3e4"
ignore@3.3.7:
ignore@3.3.7, ignore@^3.3.5:
version "3.3.7"
resolved "https://registry.yarnpkg.com/ignore/-/ignore-3.3.7.tgz#612289bfb3c220e186a58118618d5be8c1bab021"
@ -2040,6 +2082,12 @@ imurmurhash@^0.1.4:
version "0.1.4"
resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea"
indent-string@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-2.1.0.tgz#8e2d48348742121b4a8218b7a137e9a52049dc80"
dependencies:
repeating "^2.0.0"
indexes-of@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/indexes-of/-/indexes-of-1.0.1.tgz#f30f716c8e2bd346c7b67d3df3915566a7c05607"
@ -2100,6 +2148,10 @@ invert-kv@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6"
irregular-plurals@^1.0.0:
version "1.4.0"
resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-1.4.0.tgz#2ca9b033651111855412f16be5d77c62a458a766"
is-alphabetical@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/is-alphabetical/-/is-alphabetical-1.0.1.tgz#c77079cc91d4efac775be1034bf2d243f95e6f08"
@ -2440,7 +2492,7 @@ jest-docblock@^20.0.1:
version "20.0.3"
resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-20.0.3.tgz#17bea984342cc33d83c50fbe1545ea0efaa44712"
jest-docblock@^21.2.0:
jest-docblock@^21.0.0, jest-docblock@^21.2.0:
version "21.2.0"
resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-21.2.0.tgz#51529c3b30d5fd159da60c27ceedc195faf8d414"
@ -2748,6 +2800,10 @@ levn@^0.3.0, levn@~0.3.0:
prelude-ls "~1.1.2"
type-check "~0.3.2"
lines-and-columns@^1.1.6:
version "1.1.6"
resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00"
load-json-file@^1.0.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0"
@ -2799,6 +2855,12 @@ lodash@^4.0.0, lodash@^4.14.0, lodash@^4.17.4, lodash@^4.2.0, lodash@^4.3.0:
version "4.17.4"
resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae"
log-symbols@^2.0.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-2.1.0.tgz#f35fa60e278832b538dc4dddcbb478a45d3e3be6"
dependencies:
chalk "^2.0.1"
longest@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097"
@ -2809,6 +2871,13 @@ loose-envify@^1.0.0:
dependencies:
js-tokens "^3.0.0"
loud-rejection@^1.0.0:
version "1.6.0"
resolved "https://registry.yarnpkg.com/loud-rejection/-/loud-rejection-1.6.0.tgz#5b46f80147edee578870f086d04821cf998e551f"
dependencies:
currently-unhandled "^0.4.1"
signal-exit "^3.0.0"
lru-cache@^4.0.1:
version "4.1.1"
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.1.tgz#622e32e82488b49279114a4f9ecf45e7cd6bba55"
@ -2840,6 +2909,10 @@ makeerror@1.0.x:
dependencies:
tmpl "1.0.x"
map-obj@^1.0.0, map-obj@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-1.0.1.tgz#d933ceb9205d82bdcf4886f6742bdc2b4dea146d"
markdown-escapes@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/markdown-escapes/-/markdown-escapes-1.0.1.tgz#1994df2d3af4811de59a6714934c2b2292734518"
@ -2857,6 +2930,21 @@ memory-fs@^0.4.0, memory-fs@~0.4.1:
errno "^0.1.3"
readable-stream "^2.0.1"
meow@^3.7.0:
version "3.7.0"
resolved "https://registry.yarnpkg.com/meow/-/meow-3.7.0.tgz#72cb668b425228290abbfa856892587308a801fb"
dependencies:
camelcase-keys "^2.0.0"
decamelize "^1.1.2"
loud-rejection "^1.0.0"
map-obj "^1.0.1"
minimist "^1.1.3"
normalize-package-data "^2.3.4"
object-assign "^4.0.1"
read-pkg-up "^1.0.1"
redent "^1.0.0"
trim-newlines "^1.0.0"
merge@^1.1.3:
version "1.2.0"
resolved "https://registry.yarnpkg.com/merge/-/merge-1.2.0.tgz#7531e39d4949c281a66b8c5a6e0265e8b05894da"
@ -2918,7 +3006,7 @@ minimist@0.0.8, minimist@~0.0.1:
version "0.0.8"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d"
minimist@1.2.0, minimist@^1.1.1, minimist@^1.2.0:
minimist@1.2.0, minimist@^1.1.1, minimist@^1.1.3, minimist@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
@ -3015,6 +3103,15 @@ normalize-package-data@^2.3.2:
semver "2 || 3 || 4 || 5"
validate-npm-package-license "^3.0.1"
normalize-package-data@^2.3.4:
version "2.4.0"
resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.4.0.tgz#12f95a307d58352075a04907b84ac8be98ac012f"
dependencies:
hosted-git-info "^2.1.4"
is-builtin-module "^1.0.0"
semver "2 || 3 || 4 || 5"
validate-npm-package-license "^3.0.1"
normalize-path@^2.0.1:
version "2.1.1"
resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-2.1.1.tgz#1ab28b556e198363a8c1a6f7e6fa20137fe6aed9"
@ -3292,6 +3389,12 @@ pkg-dir@^1.0.0:
dependencies:
find-up "^1.0.0"
plur@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/plur/-/plur-2.1.2.tgz#7482452c1a0f508e3e344eaec312c91c29dc655a"
dependencies:
irregular-plurals "^1.0.0"
pluralize@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-4.0.0.tgz#59b708c1c0190a2f692f1c7618c446b052fd1762"
@ -3353,9 +3456,9 @@ preserve@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/preserve/-/preserve-0.2.0.tgz#815ed1f6ebc65926f865b310c0713bcb3315ce4b"
prettier@1.8.0:
version "1.8.0"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.8.0.tgz#d9dc68277cf1ded816c8e8863ab47889c29ce9a6"
prettier@1.8.2:
version "1.8.2"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.8.2.tgz#bff83e7fd573933c607875e5ba3abbdffb96aeb8"
pretty-format@^21.1.0:
version "21.1.0"
@ -3371,6 +3474,18 @@ pretty-format@^21.2.1:
ansi-regex "^3.0.0"
ansi-styles "^3.2.0"
prettylint@1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/prettylint/-/prettylint-1.0.0.tgz#b71720ad9733e098fdd8ebea90c61cda33371aa1"
dependencies:
eslint-formatter-pretty "^1.3.0"
eslint-plugin-prettier "^2.2.0"
globby "^6.1.0"
ignore "^3.3.5"
lines-and-columns "^1.1.6"
meow "^3.7.0"
tslib "^1.8.0"
private@^0.1.6, private@^0.1.7:
version "0.1.7"
resolved "https://registry.yarnpkg.com/private/-/private-0.1.7.tgz#68ce5e8a1ef0a23bb570cc28537b5332aba63ef1"
@ -3512,6 +3627,13 @@ rechoir@^0.6.2:
dependencies:
resolve "^1.1.6"
redent@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/redent/-/redent-1.0.0.tgz#cf916ab1fd5f1f16dfb20822dd6ec7f730c2afde"
dependencies:
indent-string "^2.1.0"
strip-indent "^1.0.1"
regenerate@^1.2.1:
version "1.3.2"
resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.3.2.tgz#d1941c67bad437e1be76433add5b385f95b19260"
@ -4060,6 +4182,12 @@ strip-eof@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/strip-eof/-/strip-eof-1.0.0.tgz#bb43ff5598a6eb05d89b59fcd129c983313606bf"
strip-indent@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-1.0.1.tgz#0c7962a6adefa7bbd4ac366460a638552ae1a0a2"
dependencies:
get-stdin "^4.0.1"
strip-json-comments@~2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"
@ -4189,6 +4317,10 @@ tr46@~0.0.3:
version "0.0.3"
resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a"
trim-newlines@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613"
trim-right@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003"
@ -4209,6 +4341,10 @@ tryit@^1.0.1:
version "1.0.3"
resolved "https://registry.yarnpkg.com/tryit/-/tryit-1.0.3.tgz#393be730a9446fd1ead6da59a014308f36c289cb"
tslib@^1.8.0:
version "1.8.0"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.8.0.tgz#dc604ebad64bcbf696d613da6c954aa0e7ea1eb6"
tty-browserify@0.0.0:
version "0.0.0"
resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6"