diff --git a/website/astro.config.ts b/website/astro.config.ts index adce7494e9d7..1e3d780cb715 100644 --- a/website/astro.config.ts +++ b/website/astro.config.ts @@ -66,6 +66,10 @@ export default defineConfig({ label: "简体中文", lang: "zh-CN", }, + "pt-br": { + label: "Português", + lang: "pt-BR", + }, }, sidebar: [ { label: "Home", link: "/", translations: { ja: "ホーム" } }, diff --git a/website/src/content/docs/pt-br/404.md b/website/src/content/docs/pt-br/404.md new file mode 100644 index 000000000000..aa7192eea3b1 --- /dev/null +++ b/website/src/content/docs/pt-br/404.md @@ -0,0 +1,8 @@ +--- +title: "404" +template: splash +editUrl: false +hero: + title: "404" + tagline: Biome não encontrado. Verifique a URL ou tente usar a barra de pesquisa. +--- diff --git a/website/src/content/docs/pt-br/analyzer/index.mdx b/website/src/content/docs/pt-br/analyzer/index.mdx new file mode 100644 index 000000000000..32087cb56754 --- /dev/null +++ b/website/src/content/docs/pt-br/analyzer/index.mdx @@ -0,0 +1,133 @@ +--- +title: Analyzer +description: What the Biome analyzer provides +--- + +Biome's analyzer provides a series of features that users can leverage. + +## Imports Sorting + +Biome allows to sort import statement using [natural ordering](https://en.wikipedia.org/wiki/Natural_sort_order). + +This feature is enabled by default but can be opted-out via configuration: + +```json title="biome.json" +{ + "organizeImports": { + "enabled": false + } +} +``` + +### How imports are sorted + +Import statements are sorted by "distance". Modules that are "farther" from the user are put on the top, modules "closer" to the user are put on the bottom: + +1. modules imported via `bun:` protocol. This is applicable when writing code run by Bun; +2. built-in Node.js modules that are explicitly imported using the `node:` protocol and common Node built-ins such as `assert`; +3. modules imported via `npm:` protocol. This is applicable when writing code run by Deno; +4. modules imported via URL; +5. modules imported from libraries; +6. modules imported via absolute imports; +7. modules imported from a name prefixed by `#`. This is applicable when using [Node's subpath imports](https://nodejs.org/api/packages.html#subpath-imports); +8. modules imported via relative imports; +9. modules that couldn't be identified by the previous criteria; + +For example, given the following code: + +```ts title="example.ts" +import uncle from "../uncle"; +import sibling from "./sibling"; +import express from "npm:express"; +import imageUrl from "url:./image.png"; +import assert from "node:assert"; +import aunt from "../aunt"; +import { VERSION } from "https://deno.land/std/version.ts"; +import { mock, test } from "node:test"; +import { expect } from "bun:test"; +import { internal } from "#internal"; +import { secret } from "/absolute/path"; +import React from "react"; +``` + +They will be sorted like this: + +```ts title="example.ts" + import { expect } from "bun:test"; + import assert from "node:assert"; + import { mock, test } from "node:test"; + import express from "npm:express"; + import { VERSION } from "https://deno.land/std/version.ts"; + import React from "react"; + import { secret } from "/absolute/path"; + import { internal } from "#internal"; + import aunt from "../aunt"; + import uncle from "../uncle"; + import sibling from "./sibling"; + import imageUrl from "url:./image.png"; +``` + +You can apply the sorting in two ways: via [CLI](#import-sorting-via-cli) or [VSCode extension](#import-sorting-via-vscode-extension). + +### Grouped imports + +It's widespread to have import statements in a certain order, primarily when you work on a frontend project, and you import CSS files: + +```js title="example.js" +import "../styles/reset.css"; +import "../styles/layout.css"; +import { Grid } from "../components/Grid.jsx"; +``` + +Another common case is import polyfills or shim files, that needs to stay at the top file: + +```js title="example.js" +import "../polyfills/array/flatMap"; +import { functionThatUsesFlatMap } from "./utils.js"; +``` + +In these cases, Biome will sort all these three imports, and it might happen that the order will **break** your application. + +To avoid this, create a "group" of imports. You create a "group" by adding a **new line** to separate the groups. + +By doing so, Biome will limit the sorting only to the import statements that belong to the same group: + +```js title="example.js" +// group 1, only these two files will be sorted +import "../styles/reset.css"; +import "../styles/layout.css"; + +// group 2, only this one is sorted +import { Grid } from "../components/Grid.jsx"; +``` + +```js title="example.js" +// group 1, the polyfill/shim +import "../polyfills/array/flatMap"; + +// group 2, the files tha require the polyfill/shim +import { functionThatUsesFlatMap } from "./utils.js"; +``` + +### Import sorting via CLI + +Using the command `check`, with the option `--apply`. + +```shell +biome check --apply ./path/to/src +``` + +### Import sorting via VSCode extension + +The Biome VS Code extension supports imports sorting through the "Organize Imports" code action. +By default, this action can be run using the +Alt+O keyboard shortcut, or is accessible through the _Command Palette_ (Ctrl/++P) by selecting _Organize Imports_. + +You can add the following to your editor configuration if you want the action to run automatically on save instead of calling it manually: + +```json title="biome.json" +{ + "editor.codeActionsOnSave":{ + "source.organizeImports.biome": true + } +} +``` diff --git a/website/src/content/docs/pt-br/formatter/index.mdx b/website/src/content/docs/pt-br/formatter/index.mdx new file mode 100644 index 000000000000..24d365c14292 --- /dev/null +++ b/website/src/content/docs/pt-br/formatter/index.mdx @@ -0,0 +1,349 @@ +--- +title: Formatter +description: How to use the Biome formatter. +--- + +import PackageManagerBiomeCommand from "@src/components/PackageManagerBiomeCommand.astro"; + +Biome is an opinionated formatter that has the goal to stop all ongoing debates over styles. +It follows a similar [philosophy to Prettier](https://prettier.io/docs/en/option-philosophy.html), +only supporting a few options to avoid debates over styles, turning into debates over Biome options. +It deliberately [resists the urge to add new options](https://github.com/prettier/prettier/issues/40) to prevent [bike-shed discussions](https://en.wikipedia.org/wiki/Law_of_triviality) in teams so they can focus on what really matters instead. + +## Options + +The language agnostic options supported by Biome are: + +- indent style (default: `tab`): Use spaces or tabs for indention +- tab width (default: `2`): The number of spaces per indention level +- line width (default: `80`): The column width at which Biome wraps code + +Other formatting options are available for specific languages as well. See the [configuration](/reference/configuration) options for details. + +## Use the formatter with the CLI + +By default, the formatter **checks** the code and emit diagnostics if there are changes in formatting: + + + +If you want to **apply** the new formatting, pass the `--write` option: + + + +Use the `--help` flag to know what are the available options: + + + +Or check the [CLI reference section](/reference/cli#biomeformat). + +## Configuration + +You may want to [configure Biome](/reference/configuration/#formatter) using `biome.json`. +The following defaults are applied: + +```json title="biome.json" +{ + "formatter": { + "enabled": true, + "formatWithErrors": false, + "indentStyle": "tab", + "indentWidth": 2, + "lineWidth": 80, + "ignore": [] + } +} +``` + +## Ignoring Code + +There are times when the formatted code isn't ideal. + +For these cases, you can use a format suppression comment: + +```js title="example.js" +// biome-ignore format: +``` + +Example: + +```js title="example.js" +const expr = + // biome-ignore format: the array should not be formatted + [ + (2 * n) / (r - l), + 0, + (r + l) / (r - l), + 0, + 0, + (2 * n) / (t - b), + (t + b) / (t - b), + 0, + 0, + 0, + -(f + n) / (f - n), + -(2 * f * n) / (f - n), + 0, + 0, + -1, + 0, + ]; +``` + +## Differences with Prettier + +There are some divergences with Prettier. + +### Prettier doesn't unquote some object properties that are valid JavaScript identifiers. + +Prettier and Biome unquote object and class properties that are valid JavaScript identifiers. +Prettier [unquotes only valid ES5 identifiers](https://github.com/prettier/prettier/blob/a5d502513e5de4819a41fd90b9be7247146effc7/src/language-js/utils/index.js#L646). + +This is a legacy restriction in an ecosystem where ES2015 is now widespread. +Thus, we decided to diverge here by un-quoting all valid JavaScript identifiers in ES2015+. + +A possible workaround would be to introduce a configuration to set the ECMAScript version a project uses. +We could then adjust the un-quoting behaviour based on that version. +Setting the ECMAScript version to `ES5` could match Prettier's behaviour. + +```js title="example.js" +const obj = { + 'a': true, + b: true, + "𐊧": true, +} +``` + +Diff + +```js title="exmaple.js" del={4} ins={5} +const obj = { + a: true, + b: true, + "𐊧": true, + 𐊧: true, +}; +``` + + +### Prettier has an inconsistent behavior for assignment in computed keys. + +Prettier and Biome enclose some assignment expressions between parentheses, particularly in conditionals. +This allows Biome to identify an expression that should be a comparison. + +Prettier has inconsistent behaviour because it adds parentheses for an assignment in a computed key of an object property and doesn't for a computed key of a class property, as demonstrated by the following example: + +Input + +```js title="example.js" +a = { + [x = 0]: 1, +} + +class C { + [x = 0] = 1 +} +``` + +Diff + +```js title="example.js" del={2} ins={3} +a = { + [(x = 0)]: 1, + [x = 0]: 1, +}; + +class C { + [x = 0] = 1; +} +``` + +[Playground link](https://biomejs.dev/playground?enabledLinting=false&code=YQAgAD0AIAB7AAoAIAAgAFsAeAAgAD0AIAAwAF0AOgAgADEALAAKAH0ACgAKAGMAbABhAHMAcwAgAEMAIAB7AAoAIAAgACAAIABbAHgAIAA9ACAAMABdACAAPQAgADEACgB9AAoA) + +To be consistent, we decided to diverge and omit the parentheses. +Alternatively, we could enclose any assignment in a computed key of an object or of a class. + + +### Prettier adds a trailing comma to type parameters of arrow functions even when it is not required. + +In some specific cases, a type parameter list of an arrow function requires a trailing comma to distinguish it from a JSX element. +When a default type is provided, this trailing comma is not required. +Here, we diverge from Prettier because we think it better respects the original intent of Prettier, which was to add a trailing comma only when required. + +Input + +```tsx title="example.tsx" +() => {}; +``` + +Diff + +```tsx title="example.tsx" del={1} ins={2} +() => {}; +() => {}; +``` + + +### Prettier formats invalid syntaxes + +Prettier's Babel-based parsing for JavaScript and TypeScript is very loose and [allows multiple errors](https://github.com/prettier/prettier/blob/e4a74c05f4502dd4ec70495c3130ff08ab088e05/src/language-js/parse/babel.js#L177-L218) to be ignored. +Biome's parser is intentionally stricter than the Prettier parser. +It correctly identifies the following syntax errors: + +- A function cannot have duplicate modifiers +- invalid order of properties' modifiers +- Function declarations are not allowed to have bodies +- non-abstract classes cannot have abstract properties +- An optional chain cannot be assigned +- The `const` modifier cannot be set on a type parameter of an interface +- top-level return +- etc. + +In Prettier, these errors aren't considered parse errors, and the AST is still built "correctly" with the appropriate nodes. +When formatting, Prettier treats these nodes as normal and formats them accordingly. + +In Biome, the parsing errors result in `Bogus` nodes, which may contain any number of valid nodes, invalid nodes, and/or raw characters. +When formatting, Biome treats bogus nodes as effectively plain text, printing them out verbatim into the resulting code without any formatting since attempting to format them could be incorrect and cause semantic changes. + +For class properties, Prettier's current parsing strategy also uses boolean fields for modifiers, meaning only one of each kind of modifier can ever be present (accessibility modifiers are stored as a single string). +When printing, Prettier looks at the list of booleans and decides which modifiers to print out again. Biome instead keeps a list of modifiers, meaning duplicates are kept around and can be analyzed (hence the parsing error messages about duplicate modifiers and ordering). +When printing out the bogus nodes, this list is kept intact, and printing out the unformatted text results in those modifiers continuing to exist. + +There are ways that Biome can address this. +One possibility is to try to interpret the Bogus nodes when formatting and construct valid nodes out of them. +If a valid node can be built, then it would just format that node like normal, otherwise, it prints the bogus text verbatim as it does currently. +However, this is messy and introduces a form of parsing logic into the formatter that is not meaningful. + +Another option is to introduce some form of "syntactically-valid bogus node" into the parser, which accepts these kinds of purely semantic errors (duplicate modifiers, abstract properties in non-abstract classes). + +It would continue to build the nodes like normal (effectively matching the behavior in Prettier) but store them inside of a new kind of bogus node, including the diagnostics along with it. +When formatting, these particular bogus nodes would just attempt to format the inner node and then fallback if there's an error (the existing `format_or_verbatim` utility would do this already). +This keeps the parsing and formatting logic separate from each other but introduces more complexity to the parser, allowing invalid states to be considered semi-valid. + +#### Duplicate modifiers on class properties + +Input + +```ts title="example.ts" +// Multiple accessibility modifiers +class Foo { + private public a = 1; +} + +// Declare function with body +declare function foo ( ) { } + +// Invalid use of abstract +class Bar { + abstract foo ; +} + +// Duplicate Readonly +class Read { + readonly readonly x: number; +} +``` + +Diff + +```ts title="example.ts" del={3, 8, 13, 19} ins={4, 9, 14, 20} +// Multiple accessibility modifiers +class Foo { + private a = 1; + private public a = 1; +} + +// Declare function with body +declare function foo() {}; +declare function foo ( ) { } + +// Invalid use of abstract +class Bar { + abstract foo; + abstract foo ; +} + +// Duplicate Readonly +class Read { + readonly x: number; + readonly readonly x: number; +} + + +#### Assignment to an optional chain + +Input + +```js title="example.js" +(a?.b) = c; +``` + +Diff + +```js title="example.js" del={1} ins={2} +a?.b = c; +(a?.b) = c; +``` + +#### Incorrect modifier for the type parameters of an interface + +Input + +```ts title="example.js" +interface L {} +``` + +Diff + +```ts title="example.js" del={1} ins={2} +interface L {} +interface L {} +``` + +#### Top-level return + +```js title="example.js" +return someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD +``` + +```js title="example.js" del={1, 2, 3, 4, 5, 6} ins={7} +return ( + someVeryLongStringA && + someVeryLongStringB && + someVeryLongStringC && + someVeryLongStringD +); +return someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD +``` + +#### Erroneous self-increment and self-decrement + +Input + +```js title="example.js" +(1)++; +``` + +```js title="example.js" del{1} add={2} +1++; +(1)++; +``` + +#### Use of `abstract` modifier in non-abstract classes + +Input + +```ts title="example.js" +class C { + abstract f() : number; +} +``` + +Diff + + +```ts title="example.js" del{2} add={3} +class C { + abstract f(): number; + abstract f() : number; +} +``` diff --git a/website/src/content/docs/pt-br/formatter/option-philosophy.md b/website/src/content/docs/pt-br/formatter/option-philosophy.md new file mode 100644 index 000000000000..cd5e78872e8c --- /dev/null +++ b/website/src/content/docs/pt-br/formatter/option-philosophy.md @@ -0,0 +1,38 @@ +--- +title: Formatter Option Philosophy +description: Configuring an opinionated formatter. +--- + +>💡 Biome follows the same [Option Philosophy as Prettier](https://prettier.io/docs/en/option-philosophy). The existing set of options for formatting is considered stable, and new options are not likely to be considered. +> +>This document explains some history about how and why Biome got to where it is today, and an outlook for the future. + +Biome is an *opinionated formatter*. In an ideal world, that means Biome assumes there is only one correct way to format things and will enforce that style at all times. No matter the project, no matter the setup, code formatted by Biome will always look the same. From another perspective, Biome is its own *automatic style guide*, not a tool for implementing other style guides. + +Having such a strong opinion on formatting may seem heavy-handed, but the benefits quickly become clear after adoption. All of the discussions about where spaces should go, whether a line should be broken out, whether a line should be indented, and so many more simply *vanish*. [Trivial, bike-shedding discussions](https://en.wikipedia.org/wiki/Law_of_triviality) no longer distract from focusing on what matters. Code reviews become free of re-formatting requests and cyclical debates. All it takes is trust that Biome does its best to format code cleanly, legibly, and consistently. + +Beyond the benefits within individual teams and organizations, the adoption of consistent formatters across the whole web ecosystem benefits everyone, making it easier to retain familiarity when moving between projects and helping newcomers learn and recognize patterns more intuitively without distractions. + +In the web ecosystem today, Prettier is by far the most popular code formatter, and it is also strongly opinionated, with a [strict philosophy on adding options](https://prettier.io/docs/en/option-philosophy). Biome aims to be [largely compatible with Prettier](https://biomejs.dev/blog/biome-wins-prettier-challenge), and as such, has adopted many of the opinions that Prettier implements, and configuration is no exception to that. + +Biome is proud to have reached such high compatibility with Prettier and make the migration path for users as painless as possible, but this also comes with similar caveats. + +## Existing Options + +Biome started out with a strict subset of configuration options, targeting the most common and contentious style guidelines in the JavaScript ecosystem: indent styles (tabs vs spaces), indent widths (2 spaces to equal a tab, or 4?), and enforced semicolons. Adding options for these points was considered sufficient enough to address most people’s needs, and there was no strong consideration for adding any others. + +Leaning on the [Prettier Option Philosophy](https://prettier.io/docs/en/option-philosophy), Biome had the chance to start fresh and avoid the pitfalls that Prettier had fallen into with its other existing options, like `--bracket-same-line` and `--arrow-parens`: + +> …[these] are not the type of options we’re happy to have. They cause a lot of bike-shedding in teams, and we’re sorry for that. Difficult to remove now, these options exist as a historical artifact and should not motivate adding more options (“If *those* options exist, why can’t this one?”). + +However, when the [Prettier Challenge was announced](https://twitter.com/Vjeux/status/1722733472522142022), Biome decided to accept the challenge, which required implementing all of the configuration options that Prettier had to achieve full compatibility. + +Biome still shares Prettier's philosophy about these options and considers them a legacy feature for compatibility rather than a baseline feature set. Their existence does not indicate that more options will be added, nor should they be used as a rationale to support the existence of other options in the future. + +## New Options + +Much like Prettier, Biome believes the current set of options is stable, sufficient, and not open for additions or other changes. Requests for additional configuration options are not likely to be considered and may be closed without discussion. + +That said, even as Biome has established itself as a capable and robust formatting tool, it is also still relatively new, meaning there is plenty of opportunity to pave the way for new advancements and ideas that may not seem feasible otherwise. + +The formatting style of Biome is also considered relatively stable, continuing to match Prettier as much as possible, with [few intentional deviations](https://github.com/biomejs/biome/issues/739). Changes to the style of Biome may be considered and implemented. Still, these are also unlikely to become configurable options and would instead be applied universally for all future versions of Biome. \ No newline at end of file diff --git a/website/src/content/docs/pt-br/guides/big-projects.mdx b/website/src/content/docs/pt-br/guides/big-projects.mdx new file mode 100644 index 000000000000..4452d5565904 --- /dev/null +++ b/website/src/content/docs/pt-br/guides/big-projects.mdx @@ -0,0 +1,94 @@ +--- +title: Use Biome in big projects +description: A small guide how to set Biome in big projects +--- + +Biome can provide some tools that can help you to use it properly in big projects, such as monorepo or workspaces that contain multiple projects. + + +## Use multiple configuration files + +When you use Biome's features - either with the CLI or LSP - the tool looks for the nearest configuration file using the current working directory. + +If Biome doesn't find the configuration file there, it **starts walking upwards** the directories of the file system, until it finds one. + +You can leverage this feature to apply different settings based on the project/folder. + +Let's suppose we have a project that contains a backend app and new frontend app. + + +``` +app +├── backend +│ ├── biome.json +│ └── package.json +└── frontend + ├── biome.json + ├── legacy-app + │ └── package.json + └── new-app + └── package.json +``` + +This means that when you run a script from the file `app/backend/package.json`, Biome will use the configuration file `app/backend/biome.json`. + +When you run a script from `app/frontend/legacy-app/package.json` or `app/frontend/new-app/package.json`, Biome will use the configuration file `app/frontend/biome.json`. + +## Share the configuration + +It's possible to use the [`extends`](/reference/configuration#extends) configuration option to breakdown options across files. + +Let's assume that we have these requirements: +- `legacy-app` have to format using spaces; +- `backend` and `new-app` have to format using tabs; +- all apps have to format using line width 120; +- `backend` app needs some extra linting; + +We start by creating a new configuration file at `app/biome.json`, and put there the shared options: + + +```json title="app/biome.json" +{ + "formatter": { + "enabled": true, + "lineWidth": 120 + } +} +``` + +Now let's **move** `app/frontend/biome.json` to `app/frontend/legacy-app/`, because that's where we need to use a different formatting. + + +```json title="app/frontend/legacy-app/biome.json" +{ + "formatter": { + "indentStyle": "space" + } +} +``` + +Then, we tell Biome to inherit all the options from the main `app/biome.json` file, using the `extends` property: + +```json title="app/frontend/legacy-app/biome.json" ins={2} +{ + "extends": ["../../biome.json"], + "formatter": { + "indentStyle": "space" + } +} +``` + +Let's jump to `app/backend/biome.json`, where we need to enable the linting: + + +```json title="app/backend/biome.json" +{ + "extends": ["../biome.json"], + "linter": { + "enabled": "true", + "rules": { + "recommended": true + } + } +} +``` diff --git a/website/src/content/docs/pt-br/guides/getting-started.mdx b/website/src/content/docs/pt-br/guides/getting-started.mdx new file mode 100644 index 000000000000..ebab4e359ca1 --- /dev/null +++ b/website/src/content/docs/pt-br/guides/getting-started.mdx @@ -0,0 +1,105 @@ +--- +title: Primeiros passos +description: Aprenda a criar um novo projeto com Biome. +--- + +import PackageManagerBiomeCommand from "@src/components/PackageManagerBiomeCommand.astro"; +import PackageManagerCommand from "@src/components/PackageManagerCommand.astro"; + +## Requisitos + +- Windows (incluindo WSL), macOS, ou Linux +- x86_64 ou ARM64 +- Node.js v14.18 ou mais recente (não aplicável se você utilizar o executável independente) + +## Instalação + +A forma mais rápida de baixar o Biome é usando `npm` ou o seu package manager favorito. O CLI também está disponível como um [executável independente](/guides/manual-installation) caso você queira usar Biome sem instalar o Node.js. + +Para instalar o Biome, execute o seguinte comando em um diretório que possua o arquivo `package.json`. + + + +:::note +É possível instalar o Biome de forma global em vez de local. +Mas isso não é recomendado. +::: + +É **altamente recomendado** não utilizar "range operators" ao instalar o Biome. +Dê uma olhada na [página de versionamento](/pt-br/internals/versioning/) para mais informações. + +## Configuração + +Recomendamos criar um arquivo de configuração `biome.json` para cada projeto. +Isso elimina a necessidade de repetir as opções do CLI toda vez que você executar um comando e garante que o Biome aplique as mesmas configurações em seu editor. Se você está contente com a configuração padrão, você não precisa fazer isso. + +Para criar o arquivo de configuração, use o comando de `init` dentro da pasta raíz do seu projeto: + + + +Após utilizar o comando, você terá um novo arquivo `biome.json` no seu diretório: + +```json title="biome.json" +{ + "$schema": "https://biomejs.dev/schemas/1.4.0/schema.json", + "organizeImports": { + "enabled": false + }, + "linter": { + "enabled": true, + "rules": { + "recommended": true + } + } +} +``` + +O `linter.enabled: true` habilita o linter e o `rules.recommended: true` habilita as [regras recomendadas](/linter/rules/). + +A formatação está ativada porque a configuração não [desabilita](/reference/configuration/#formatterenabled) explicitamente a formatação com `formatter.enabled: false`. + +## Como usar + +O CLI do Biome vem com vários comandos e opções, então você utiliza só o que precisar. + +Você pode formatar arquivos e diretórios usando o comando [`format`](/reference/cli#biome-format) com o parâmetro `--write`: + + + +Você pode analisar e aplicar [correções seguras](/pt-br/linter#correções-seguras) em arquivos e diretórios utilizando o comando [`lint`](/reference/cli#biome-lint) com o parâmetro `--apply`: + + + +Você pode aplicar **ambos** com o comando [`check`](/reference/cli#biome-check) + + + +O comando `check` executa múltiplas ferramentas de uma vez. Até o momento, ele: + +- formata arquivos +- analisa arquivos +- organiza as importações + +## Instale um plugin de editor + +Recomendamos instalar um plugin de editor para aproveitar ao máximo o Biome. Dê uma olhada na [página de editores](/pt-br/guides/integrate-in-editor) para saber qual oferece suporte ao Biome. + +## Configuração para integração contínua (CI) + +Se você está usando Node.js, a forma recomendada de executar o Biome em CI é utilizando o seu [package manager favorito](/pt-br/guides/getting-started#instalação). +Isso garante que sua pipeline de integração contínua (CI) utilize a mesma versão do Biome que você usa dentro do editor ou ao executar comandos locais pelo CLI. + +## Próximos passos + +Parabéns! Agora você está pronto para utilizar o Biome. 🥳 + +- Saiba mais sobre como usar e configurar o [formatter](/formatter) +- Saiba mais sobre como usar e configurar o [linter](/pt-br/linter) +- Familiarize-se com as [opções do CLI](/reference/cli) +- Familiarize-se com as [opções de configuração](/reference/configuration) +- Entre na nossa [comunidade do Discord](https://discord.gg/BypW39g6Yc) diff --git a/website/src/content/docs/pt-br/guides/how-biome-works.mdx b/website/src/content/docs/pt-br/guides/how-biome-works.mdx new file mode 100644 index 000000000000..0b3781e674ec --- /dev/null +++ b/website/src/content/docs/pt-br/guides/how-biome-works.mdx @@ -0,0 +1,96 @@ +--- +title: How Biome works +description: Learn how to set up a new project with Biome. +--- +import DefaultConfiguration from "@src/components/generated/DefaultConfiguration.mdx"; + + +## Configuration + +The configuration file is considered **optional**, Biome has good defaults. Use the configuration +file to change those defaults. + +The Biome configuration file is named `biome.json` and should be placed in the root directory of your project. The root +directory is usually the directory containing your project's `package.json`. + +This configuration file enables the formatter and sets the preferred indent style and width. The linter is disabled: + +```json title="biome.json" +{ + "formatter": { + "enabled": true, + "indentStyle": "tab", + "lineWidth": 120 + }, + "linter": { + "enabled": false + } +} +``` + +### Default configuration + +When you run `biome init`, the default configuration emitted is the following: + + + +### Configuration file resolution + +Biome uses auto discovery to find the nearest `biome.json` file. It starts looking for `biome.json` in the current +working directory, and then it starts looking in the parent directories until: +- it finds a `biome.json` file; +- it applies Biome's defaults if **no `biome.json` is found**; + +Here's an example: + +``` +└── app + ├── backend + │ ├── package.json + │ └── biome.json + └── frontend + ├── legacy + │ └── package.json + ├── new + │ └── package.json + └── biome.json + +``` + +- biome commands that run in `app/backend/package.json` will use the configuration file `app/backend/biome.json`; +- biome commands that run in `app/frontend/legacy/package.json` and `app/frontend/new/package.json` +will use the configuration file `app/frontend/biome.json`; + + +## Known Files + +The following files are currently ignored by Biome. This means that no diagnostics will be ever emitted by Biome for those files. + +- `package.json` +- `package-lock.json` +- `npm-shrinkwrap.json` +- `yarn.lock` +- `composer.json` +- `composer.lock` +- `typescript.json` +- `tsconfig.json` +- `jsconfig.json` +- `deno.json` +- `deno.jsonc` + + + +The following files are parsed as **`JSON` files** with the options `json.parser.allowComments` and `json.parser.allowTrailingCommas` set to `true`. This is because editor tools like VSCode treat them like this. + +- `tslint.json` +- `babel.config.json` +- `.babelrc.json` +- `.ember-cli` +- `typedoc.json` +- `.eslintrc` +- `.eslintrc.json` +- `.jsfmtrc` +- `.jshintrc` +- `.swcrc` +- `.hintrc` +- `.babelrc` diff --git a/website/src/content/docs/pt-br/guides/integrate-in-editor.mdx b/website/src/content/docs/pt-br/guides/integrate-in-editor.mdx new file mode 100644 index 000000000000..b3cef27de377 --- /dev/null +++ b/website/src/content/docs/pt-br/guides/integrate-in-editor.mdx @@ -0,0 +1,135 @@ +--- +title: Integrate Biome in your editor +description: Learn how you can integrate Biome with editors and IDEs +--- + +## First-party plugins + +These are plugins that are maintained by the Biome team and part of the [Biome organization](https://github.com/biomejs). + +### VS Code + +The Biome editor integration allows you to: + +* Format files on save or when issuing the Format command. +* Lint files and apply code fixes + +Install our official [Biome VS Code extension](https://marketplace.visualstudio.com/items?itemName=biomejs.biome) from the Visual Studio Marketplace. + +To make Biome the default formatter open a [supported file](/internals/language-support/) and: + +* open the *Command Palette* (View or Ctrl/++P) +* select *Format Document With...* +* select *Configure Default Formatter* +* select *Biome*. + +### IntelliJ + +To install the Biome IntelliJ plugin, head over to [official plugin page](https://plugins.jetbrains.com/plugin/22761-biome) or follow these steps: + +**From JetBrains IDEs:** + +1. Open IntelliJ IDEA. +2. Go to **Settings/Preferences**. +3. Select **Plugins** from the left-hand menu. +4. Click on the **Marketplace** tab. +5. Search for "Biome" and click **Install**. +6. Restart the IDE to activate the plugin. + +**From disk:** + +1. Download the plugin .zip from releases tab. +2. Press `⌘Сmd,` to open the IDE settings and then select Plugins. +3. On the Plugins page, click The Settings button and then click Install Plugin from Disk…. + +## Third-party plugins + +These are plugin maintained by other communities, that you install in your editor: +- [`neovim`](https://neovim.io/): you'll have to install [`nvim-lspconfig`](https://github.com/neovim/nvim-lspconfig/), and follow the [instructions](https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#biome); +- [`helix`](https://helix-editor.com/): follow the instruction of [this manual](https://github.com/biomejs/biome/blob/main/editors/helix/manual.md) +- [`coc-biome`](https://github.com/fannheyward/coc-biome): Biome extension for [`coc.nvim`](https://github.com/neoclide/coc.nvim) +- [`sublime text`](http://www.sublimetext.com/): follow the [`LSP-biome`](https://github.com/sublimelsp/LSP-biome) installation instructions + +:::note +Is there a plugin for an editor that isn't listed here? Please file a PR and we will be happy to add it to the list +::: + +## Write your own plugin + +Biome has [LSP](https://microsoft.github.io/language-server-protocol/) first-class support. If your editor does implement LSP, then the integration of Biome should be seamless. + +### Use the LSP proxy + +Biome has a command called `lsp-proxy`. When executed, Biome will spawn two processes: +- a [daemon](/internals/architecture#daemon) that does execute the requested operations; +- a server that functions as a proxy between the requests of the client - the editor - and the server - the daemon; + +If your editor is able to interact with a server and send [JSON-RPC](https://www.jsonrpc.org/) request, you only need to configure the editor run that command. + +You can check how the [`neo-vim biome plugin`](https://github.com/neovim/nvim-lspconfig/blob/master/lua/lspconfig/server_configurations/biome.lua) does it. + +### Use `stdin` + +If your editor doesn't support LSP, you use directly the binary `biome` and call it using [standard input](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)). + +The following commands can be called via standard input: +- [`format`](/reference/cli/#biome-format) +- [`lint`](/reference/cli/#biome-lint) +- [`check`](/reference/cli/#biome-check) + +Biome will return the new output (or the original output if changes haven't occurred) to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) and the diagnostics to [standard error](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)). + +When you use `stdin`, you must pass the `--stdin-file-path` option. The file `path` **doesn't need to exist** in your file system, it can be any name. **What's important** is to provide the correct file extension, so Biome knows **how to treat** your file. + +It's the editor's responsibility to locate the resolve the path of the binary and then call it when it's needed. The binaries are shipped to npm based on the architectures and OS that we support: + +- `@biomejs/cli-darwin-arm64` +- `@biomejs/cli-darwin-x64` +- `@biomejs/cli-linux-arm64` +- `@biomejs/cli-linux-x64` +- `@biomejs/cli-win32-arm64` +- `@biomejs/cli-win32-x64` + +The binary name is `biome` or `biome.exe`, and it can be found in the root directory of the library, e.g.: `@biomejs/cli-darwin-arm64/biome`, `@biomejs/cli-win32-x64/biome.exe`. + +### Use the daemon with the binary + +Using the binary via CLI is very efficient, although you won't be able to provide [logs](#daemon-logs) to your users. The CLI allows you to bootstrap a daemon and then use the CLI commands through the daemon itself. + +If order to do so, you first need to start a daemon process with the [`start`](/reference/cli#biome-start) command: + +```shell +biome start +``` +Then, every command needs to add the `--use-server` options, e.g.: + +```shell +echo "console.log('')" | biome format --use-server --stdin-file-path=dummy.js +``` + +:::note +If you decide to use the daemon, you're also responsible to restart/kill the process with the [`stop`](/reference/cli#biome-stop) command, to avoid having ghost processes. +::: + +:::caution +Operations via the daemon are significantly slower than the CLI itself, so it's advised to run operations only on single files. +::: + +### Daemon logs + +The Biome daemon saves logs in your file system. Logs are store in a folder called `biome-logs`. You can find this folder in the temporary directory of your operating system. + +From Windows, using a powershell: +```shell +$env:TEMP +``` + +From Linux/macOS, using a terminal: + +```shell +echo $TMPDIR +``` + +The log files are rotated on an hourly basis. + + diff --git a/website/src/content/docs/pt-br/guides/manual-installation.mdx b/website/src/content/docs/pt-br/guides/manual-installation.mdx new file mode 100644 index 000000000000..2788ce07a2d6 --- /dev/null +++ b/website/src/content/docs/pt-br/guides/manual-installation.mdx @@ -0,0 +1,67 @@ +--- +title: Manual installation +description: Install the Biome manually +--- + +## Use Biome without Node.js + +Using Biome's standalone CLI binary can be a great choice if you aren't already using Node or npm (or any other package manager). +Or in other words, Biome shouldn't be the only reason for you to have a `package.json`. + +:::note +If you're already using npm or another package manager, then using the package manager is the [preferred way to install](/guides/getting-started#installation) Biome. +You're already familiar with the tooling, and installing and updating are simpler. +::: + +### Homebrew + +Biome is available as a [Homebrew formula](https://formulae.brew.sh/formula/biome) for macOS and Linux users. + +```shell +brew install biome +``` + +## System Requirements + +- Windows (including WSL), macOS, or Linux +- x86_64 or ARM64 + +## Supported platforms + +You have to pick the correct binary for your platform for Biome work. The following table should help you do so. + +| CPU Architecture | Windows | macOS | Linux | Linux (musl) | +| ---------------- | ------------- | ---------------------------- | ------------- | ------------------ | +| `arm64` | `win32-arm64` | `darwin-arm64` (M1 or newer) | `linux-arm64` | `linux-arm64-musl` | +| `x64` | `win32-x64` | `darwin-x64` | `linux-x64` | `linux-x64-musl` | + +:::note +Use the Linux variant for Windows Subsystem for Linux (WSL). +::: + +## Install Biome + +To install Biome, grab the executable for your platform from the [latest CLI release](https://github.com/biomejs/biome/releases) on GitHub and give it execution permission. + +```shell +# macOS arm (M1 or newer) +curl -L https://github.com/biomejs/biome/releases/download/cli%2Fv/biome-darwin-arm64 -o biome +chmod +x biome + +# Linux (x86_64) +curl -L https://github.com/biomejs/biome/releases/download/cli%2Fv/biome-linux-x64 -o biome +chmod +x biome + +# Windows (x86_64, Powershell) +Invoke-WebRequest -Uri "https://github.com/biomejs/biome/releases/download/cli%2Fv/biome-win32-x64.exe" -OutFile "biome.exe" +``` + +:::note +Make sure to replace `` with the Biome version you want to install. +::: + +Now you can use Biome by simply running `./biome`. + +## Next Steps + +Read more about how to use Biome in our [getting started section](/guides/getting-started#next-steps). diff --git a/website/src/content/docs/pt-br/index.mdx b/website/src/content/docs/pt-br/index.mdx new file mode 100644 index 000000000000..2809be8da9ac --- /dev/null +++ b/website/src/content/docs/pt-br/index.mdx @@ -0,0 +1,67 @@ +--- +title: Biome +head: + - tag: title + content: Biome +template: splash +description: Formate, verifique erros e muito mais em uma fração de segundo. +hero: + title: Um conjunto de ferramentas para seu projeto web + tagline: Formate, verifique erros e muito mais em uma fração de segundo. + image: + alt: Biome, conjunto de ferramentas da web + file: ../../../assets/biome-logo-slogan.svg + actions: + - text: Vamos lá? + link: /pt-br/guides/getting-started/ + icon: right-arrow + variant: primary + - text: Veja no GitHub + link: https://github.com/biomejs/biome + icon: external + variant: secondary +banner: + content: | + Biome ganhou a recompensa do desafio do Prettier! +--- + +import { Card, CardGrid } from "@astrojs/starlight/components"; + + + + Construído com Rust e uma arquitetura inovadora inspirado pelo + rust-analyzer. + + + Nenhuma configuração é necessária para começar a usar! Caso precise, temos + diversas opções disponíveis! + + + Projetado para suportar codebases de qualquer tamanho. Focado no crescimento + do projeto, em vez de suas ferramentas. + + + Com uma integração interna eficiente, conseguimos reutilizar trabalhos + anteriores, e qualquer melhoria em uma ferramenta beneficia todas elas. + + + Esqueça aquelas mensagens de erro obscuras! Quando alguma coisa está errada, + nós falamos exatamente o que está errado e como consertar! + + + Suporte pronto para todas as funcionalidades de linguagem que você utiliza + atualmente. Suporte de primeira classe para TypeScript e JSX. + + + +## Patrocinadores + + diff --git a/website/src/content/docs/pt-br/internals/architecture.mdx b/website/src/content/docs/pt-br/internals/architecture.mdx new file mode 100644 index 000000000000..3564cc1571aa --- /dev/null +++ b/website/src/content/docs/pt-br/internals/architecture.mdx @@ -0,0 +1,153 @@ +--- +title: Architecture +description: How Biome works under the hood. +--- + +This document covers some of the internals of Biome, and how they are used inside the project. + +## Parser and CST + +The architecture of the parser is bumped by an internal fork of [rowan], a library +that implements the [Green and Red tree] pattern. + +The CST (Concrete Syntax Tree) is data structure very similar to AST (Abstract Syntax Tree) that keeps track of all the information of a program, trivia included. + +**Trivia** are represented by all that information that are important to a program to run: +- spaces +- tabs +- comments + +Trivia are attached to a node. A node can have leading trivia and trailing trivia. If you read code from left-to-right, leading trivia appear before a keyword, and trialing trivia appear after a keyword. + +Leading trivia and trailing trivia are categorized as follows: +- Every trivia up to the token/keyword (including line breaks) will be the **leading trivia**; +- Everything until the next linebreak (but not including it) will be the **trailing trivia**; + +Given the following JavaScript snippet, `// comment 1` is a trailing trivia of the token `;`, and `// comment 2` is a leading trivia to the keyword `const`. Below a minimized version of the CST represented by Biome: : + +```js +const a = "foo"; // comment 1 +// comment 2 +const b = "bar"; +``` + +``` +0: JS_MODULE@0..55 + ... + 1: SEMICOLON@15..27 ";" [] [Whitespace(" "), Comments("// comment 1")] + 1: JS_VARIABLE_STATEMENT@27..55 + ... + 1: CONST_KW@27..45 "const" [Newline("\n"), Comments("// comment 2"), Newline("\n")] [Whitespace(" ")] + 3: EOF@55..55 "" [] [] +``` + +The CST is never directly accessible by design, a developer can read its information using the Red tree, using a number of APIs that are autogenerated from the grammar of the language. + + +#### Resilient and recoverable parser + +In order to construct a CST, a parser needs to be error resilient and recoverable: +- resilient: a parser that is able to resume parsing after encountering syntax error that belong to the language; +- recoverable: a parser that is able to **understand** where an error occurred, and being able to resume the parsing by creating **correct** information; + +The recoverable part of the parser is not a science, and there aren't any rules set on stone. This means that depending on what the parser was parsing and where an error occurred, the parser might be able to recover itself in an expected ways. + +To protect the consumers from consuming incorrect syntax, the parser also uses `Bogus` nodes. These nodes are used decorate the broken code caused by an syntax error. + +In the following example, the parenthesis in the `while` are missing, although parser is able to recover itself in a good manner, and it's able to represent the code with a decent CST. The parenthesis and condition of the loop are marked as missing, and the code block is correctly parsed: + + +```js +while {} +``` + +``` +JsModule { + interpreter_token: missing (optional), + directives: JsDirectiveList [], + items: JsModuleItemList [ + JsWhileStatement { + while_token: WHILE_KW@0..6 "while" [] [Whitespace(" ")], + l_paren_token: missing (required), + test: missing (required), + r_paren_token: missing (required), + body: JsBlockStatement { + l_curly_token: L_CURLY@6..7 "{" [] [], + statements: JsStatementList [], + r_curly_token: R_CURLY@7..8 "}" [] [], + }, + }, + ], + eof_token: EOF@8..8 "" [] [], +} +``` + +This is error emitted during parsing: + +``` +main.tsx:1:7 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ✖ expected `(` but instead found `{` + + > 1 │ while {} + │ ^ + + ℹ Remove { +``` + +The same can't be said for the following snippet. The parser can't properly understand the syntax during the recovery phase, so it needs to rely on the bogus nodes to mark some syntax as erroneous. Notice the `JsBogusStatement`: + +```js +function} +``` + +``` +JsModule { + interpreter_token: missing (optional), + directives: JsDirectiveList [], + items: JsModuleItemList [ + TsDeclareFunctionDeclaration { + async_token: missing (optional), + function_token: FUNCTION_KW@0..8 "function" [] [], + id: missing (required), + type_parameters: missing (optional), + parameters: missing (required), + return_type_annotation: missing (optional), + semicolon_token: missing (optional), + }, + JsBogusStatement { + items: [ + R_CURLY@8..9 "}" [] [], + ], + }, + ], + eof_token: EOF@9..9 "" [] [], +} +``` + +This is the error we get from the parsing phase: + +``` +main.tsx:1:9 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ✖ expected a name for the function in a function declaration, but found none + + > 1 │ function} + │ ^ +``` + +## Formatter (WIP) + +## Linter (WIP) + +## Daemon (WIP) + +Biome uses a server-client architecture to run its tasks. + +A [daemon] is a long-running server +that Biome spawns in the background and uses to process requests from the editor and CLI. + + +[rowan]: https://github.com/rust-analyzer/rowan +[Green and Red tree]: https://learn.microsoft.com/en-us/archive/blogs/ericlippert/persistence-facades-and-roslyns-red-green-trees +[daemon]: https://en.wikipedia.org/wiki/Daemon_(computing) diff --git a/website/src/content/docs/pt-br/internals/credits.mdx b/website/src/content/docs/pt-br/internals/credits.mdx new file mode 100644 index 000000000000..0dd7435edba6 --- /dev/null +++ b/website/src/content/docs/pt-br/internals/credits.mdx @@ -0,0 +1,60 @@ +--- +title: Credits +description: Previous contributors and acknowledgments for projects that inspire us. +--- + +import Contributors from "@src/components/Contributors.astro"; + + + +## Acknowledgements + +Biome contains code that is heavily inspired from other projects. They have been adapted to Biome's +language/infrastructure. + +- [Prettier](https://github.com/prettier/prettier/) + - [LICENSE](https://github.com/biomejs/biome/blob/main/crates/biome_js_formatter/LICENSE) + +## Forks + +Biome is a community fork of [Rome Tools](https://github.com/biomejs/biome/). +_Rome Tools_ and _Biome_ are licensed under The MIT license. + +Biome contains code forked from other projects. +They have been transformed in some way, sometimes substantially rewritten. + +- [`crates/biome_diagnostics`](https://github.com/biomejs/biome/tree/main/crates/biome_diagnostics) + - **Original**: [`rslint/rslint_errors`](https://github.com/rslint/rslint/tree/master/crates/rslint_errors) + - **License**: MIT + +- [`crates/biome_console/src/codespan`](https://github.com/biomejs/biome/tree/main/crates/biome_console/src/codespan) + - **Original**: [`brendanzab/codespan`](https://github.com/brendanzab/codespan) + - **License**: Apache License, Version 2.0 + +- [`crates/biome_js_parser`](https://github.com/biomejs/biome/tree/main/crates/biome_js_parser) + - **Original**: [`rslint/rslint_parser`](https://github.com/rslint/rslint/tree/master/crates/rslint_parser) + - **License**: MIT + +- [`crates/biome_js_parser/lexer`](https://github.com/biomejs/biome/tree/main/crates/biome_js_parser/src/lexer) + - **Original**: [`rslint/rslint_lexer`](https://github.com/rslint/rslint/tree/master/crates/rslint_lexer) + - **License**: MIT + +- [`crates/biome_js_syntax`](https://github.com/biomejs/biome/tree/main/crates/biome_js_syntax) + - **Original**: [`rslint/rslint_syntax`](https://github.com/rslint/rslint/tree/master/crates/rslint_syntax) + - **License**: MIT + +- [`crates/biome_text_edit`](https://github.com/biomejs/biome/tree/main/crates/biome_text_edit) + - **Original**: [`rslint/rslint_text_edit`](https://github.com/rslint/rslint/tree/master/crates/rslint_text_edit) + - **License**: MIT + +- [`crates/biome_rowan`](https://github.com/biomejs/biome/tree/main/crates/biome_rowan) + - **Original**: [`rust-analyzer/rowan`](https://github.com/rust-analyzer/rowan) + - **License**: Apache License, Version 2.0 + +- [`crates/biome_text_size`](https://github.com/biomejs/biome/tree/main/crates/biome_text_size) + - **Original**: [`rust-analyzer/text-size`](https://github.com/rust-analyzer/text-size) + - **License**: Apache License, Version 2.0 or MIT + +- [`crates/biome_service/src/ignore/pattern`](https://github.com/biomejs/biome/tree/main/crates/biome_service/src/ignore/pattern) + - **Original**: [`rust-lang/glob`](https://github.com/rust-lang/glob/blob/master/src/lib.rs) + - **License**: Apache License, Version 2.0 or MIT diff --git a/website/src/content/docs/pt-br/internals/language-support.mdx b/website/src/content/docs/pt-br/internals/language-support.mdx new file mode 100644 index 000000000000..b563d9c69448 --- /dev/null +++ b/website/src/content/docs/pt-br/internals/language-support.mdx @@ -0,0 +1,34 @@ +--- +title: Language support +description: Languages and features supported by Biome. +--- + +| Language | Parsing | Formatting | Linting | +|-----------------------------------------|---------------------------------------------------------|---------------------------------------------------------|---------------------------------------------------------| +| [JavaScript](#javascript-support) | | | | +| [TypeScript](#typescript-support) | | | | +| JSX | | | | +| JSON | | | | +| JSONC | | | | +| HTML | 🚫 | 🚫 | 🚫 | +| [Vue](#html-super-languages-support) | 🚫 | 🚫 | 🚫 | +| [Svelte](#html-super-languages-support) | 🚫 | 🚫 | 🚫 | +| CSS | ⌛️ | 🚫 | 🚫 | +| Markdown | 🚫 | 🚫 | 🚫 | + + +## JavaScript support + +Biome supports the ES2023 version of the language. + +Biome supports only the official syntax. The team starts development of the new syntax when a proposal reaches +[Stage 3](https://github.com/tc39/proposals#stage-3). + +## TypeScript support + +Biome supports TypeScript version 5.2. + +## HTML super languages support + +These languages require CSS, HTML and JavaScript parsing to be supported properly. Once those parsers are +available, the works around these super languages can start. diff --git a/website/src/content/docs/pt-br/internals/philosophy.mdx b/website/src/content/docs/pt-br/internals/philosophy.mdx new file mode 100644 index 000000000000..b73eaa8fd532 --- /dev/null +++ b/website/src/content/docs/pt-br/internals/philosophy.mdx @@ -0,0 +1,42 @@ +--- +title: Philosophy +description: How we think about building Biome. +--- + +This list includes general ethos that the project should abide by. +This list is not comprehensive. Some of these are obvious but are stated for completeness. + +## Project Management + +- **Set clear expectations.** Make project intent and decisions known well in advance. + Nothing should be a surprise. + +- **Clear messaging of decisions.** The team might evaluate options and make decisions using private channels. + While the team will try to keep discussions using public channels like [GitHub discussions](https://github.com/biomejs/biome/discussions) or [Discord](https://discord.gg/BypW39g6Yc), frequent private check-in are the norm, due to the nature of the private company. + When decisions occur via private channels, the team has to commit to communicate these decisions using the public channels. + +## Technical + +- **Errors should suggest fixes and hints where possible.** These should be inferred and filtered from usage to reduce surfacing irrelevant and unhelpful messages. + +- **Unique and specific error messages.** No generic error messages. + This helps users understand what went wrong and should provide maintainers with a unique call site and the necessary information to debug. + +- **Optimise API.** Question the existence of all options and flags. + Are they necessary? Can they be combined? How can we reduce code branching? + +- **Reduce jargon.** Don't assume that users will understand specific terminology. + Strive to provide precise meaning for experts and beginners. + For example, use "character" where you would traditionally use "token" when producing parser errors. + +- **Utilize verbosity when naming commands and flags.** No unnecessary and confusing abbreviations. + +- **Use inclusive terminology.** Use gender-neutral pronouns. No ableist slurs. + No usage of terms that could be considered insensitive. + +- **Build for generic clients.** Don't assume that a terminal will only consume output using ANSI codes. + Use abstractions that could be generalized for viewing in an IDE, browser, or other environments. + +- **Terminal output should be unambiguous.** When designing terminal output, don't rely purely on formatting cues like color. + Always use a combination of formatting, symbols, and spacing. + If all ANSI codes are stripped, all the output should still be understood. diff --git a/website/src/content/docs/pt-br/internals/versioning.mdx b/website/src/content/docs/pt-br/internals/versioning.mdx new file mode 100644 index 000000000000..983e565581a9 --- /dev/null +++ b/website/src/content/docs/pt-br/internals/versioning.mdx @@ -0,0 +1,49 @@ +--- +title: Versioning +description: How we version Biome. +--- + +Fixes to lint rules, formatting layouts, etc. might prevent your scripts from passing. Due to the nature of these changes, +it's **highly recommended** to save the _exact_ version in your `package.json`, instead of using range operators. + +This methodology will make sure that your script won't fail unexpectedly. + +## Semantic Versioning + +Biome follows [semantic versioning](https://semver.org/). Due to the nature of Biome as a toolchain, it can be unclear what changes are considered major, minor, or patch. That's why Biome uses the following versioning guide: + +### Patch Release + +* Fixing a lint rule that raises lint errors for valid code (false positives) +* Fixing incorrect code suggestions +* Fixing the formatting of a syntax that results in invalid code or changes the semantics of the program. +* Improvements to the documentation +* Internal changes that don't change Biome's functionality: + * Refactors + * Performance improvements + * Increase or change in test coverage +* Improving the wording of diagnostics or fixing the rendering of diagnostics. +* Re-releases after a failed release +* Changing the formatting of established syntax. + +### Minor Release + +* Adding a new rule or promoting an existing lint rule to a stable group that is not recommended by default. +* Adding linting and formatting support for a recently introduced language feature, even if that results in more reported linting errors. +* Removal of recommended rules +* Deprecation of existing rules +* Adding new configuration optional configuration options that do not change the formatting or report more lint errors. +* Adding a new recommended lint rule or promoting an existing lint rule from the nursery group to a recommended lint rule in a stable group. +* Removal of a non-*nursery* rule or demoting a rule to the *nursery* group. + +### Major Release +* Changes to the configuration that result in different formatting or more reported lint errors (adding/removing options, changing the default value) +* Changes to Biome's public API +* Promotion of new features or tools that require some spotlight + +## Visual Studio Code Extension + +Visual Studio Code [doesn't support pre-release tags](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#prerelease-extensions) for extensions. That's why Biome uses the following version schema to distinguish stable and previews: +* Stable releases use even version numbers: 10, 12, 14, 16, ... +* Previews use odd version numbers: 11, 13, 15, 17, ... + diff --git a/website/src/content/docs/pt-br/linter/index.mdx b/website/src/content/docs/pt-br/linter/index.mdx new file mode 100644 index 000000000000..e5a491469eb6 --- /dev/null +++ b/website/src/content/docs/pt-br/linter/index.mdx @@ -0,0 +1,178 @@ +--- +title: Linter +description: Como utilizar o Linter do Biome. +--- + +import NumberOfRules from "@src/components/generated/NumberOfRules.astro"; +import RecommendedRules from "@src/components/generated/RecommendedRules.astro"; + +O Linter do Biome analisa de forma estática o seu código para encontrar erros comuns e ajudar você a escrever códigos idiomáticos. + + + +## Usar o Linter via CLI + +Você pode começar executando a CLI para verificar possíveis erros usando o seguinte comando: + +```shell +biome lint ./src +``` + +Para mais informações sobre todas as opções disponíveis, veja a página sobre [o CLI](/reference/cli#biome-lint) + +## Princípios das Regras + +Nós acreditamos que as regras devem ser informativas e que expliquem ao usuário porque uma regra é acionada, além de orientar o usuário sobre o que deve ser feito para corrigí-lo. Uma regra deve seguir esses **princípios**: + +1. Explicar o erro para o usuário. Geralmente, essa é a mensagem do diagnóstico. +2. Explicar para o usuário porque o erro foi acionado. Geralmente, isso é implementado com um parâmetro adicional. +3. Falar para o usuário o que ele precisa fazer. Geralmente, isso é implementado usando uma ação no código. Se uma ação no código não for aplicável uma nota deve dizer o que o usuário precisa fazer para arrumar o erro. + +Se você acha que uma regra não siga esses princípios, por favor [abra uma Issue](https://github.com/biomejs/biome/issues/new?assignees=&labels=S-To+triage&projects=&template=01_bug.yml&title=%F0%9F%90%9B+%3CTITLE%3E). + +## Correções de código + +As regras de Lint podem fornecer correções automáticas de código. O Biome classifica as correções em dois tipos. + +### Correções seguras + +As correções seguras não alteram a semântica do seu código. Elas podem ser aplicadas sem uma análise explicita. + +Para aplicar _correções seguras_, utilize o parâmetro `--apply`: + +```shell +biome check --apply ./src +``` + +### Correções não seguras + +Correções não seguras podem alterar a semântica do seu código. Portanto, é aconselhável revisar manualmente as alterações. + +Para aplicar _correções não seguras_, utilize o parâmetro `--apply-unsafe`: + +```shell +biome check --apply-unsafe ./src +``` + +## Regras recomendadas + +Quando o Linter está ativado, ele recomenda uma série de regras. Essas regras emitirão diagnósticos de erro. Veja as regras recomendadas logo abaixo: + + + +## Ignorando um erro + +As vezes você só quer ignorar um erro de lint em uma linha específica de código. +Você pode fazer isso usando um comentário de supressão acima da linha que emite o diagnóstico. + +Os comentários de supressão segue o seguinte formato: + +```js +// biome-ignore lint: +// biome-ignore lint/suspicious/noDebugger: +``` + +Onde + +- `biome-ignore` é o começo de um comentário de supressão; +- `lint` desativa o linter; +- `/suspicious/noDebugger`: **opcional**, grupo e o nome da regra que você quer desativar; +- `` explicação do motivo pelo qual a regra está desativada + +Aqui está um exemplo: + +```ts +// biome-ignore lint: reason +debugger; +// biome-ignore lint/suspicious/noDebugger: reason +debugger; +``` + +## Configuração + +### Ativar uma regra do Lint + +As regras recomendadas são ativadas por padrão e emitem diagnósticos com a severidade do erro. +Regras que não são recomendadas são desativadas por padrão, mas podem ser ativadas pelo arquivo de configuração. +Os diagnósticos emitidos por essas regras são mostrados com a gravidade de aviso (warning) na documentação. + +Para ativar essas regras, você precisa alterar a gravidade do diagnóstico baseado nas suas necessidades: + +```json title="biome.json" +{ + "linter": { + "enabled": true, + "rules": { + "style": { + "useBlockStatements": "error", + "useShorthandArrayType": "error", + "noShoutyConstants": "warn" + } + } + } +} +``` + +### Desativar uma regra do Lint + +Apenas adicione `"off"` como um valor dentro da configuração da regra. Por exemplo: + +```json title="biome.json" +{ + "linter": { + "enabled": true, + "rules": { + "suspicious": { + "noCommentText": "off" + }, + "style": { + "noUnusedTemplateLiteral": "off" + } + } + } +} +``` + +### Alterar a gravidade do diagnóstico + +A maioria das regras do Biome vão emitir um **erro**, mas você pode alterar isso. +Apenas adicione `"warn"` como um valor da regra. Exemplo: + +```json title="biome.json" +{ + "linter": { + "enabled": true, + "rules": { + "suspicious": { + "noCommentText": "warn" + } + } + } +} +``` + +Isso é útil em casos onde está rolando uma refatoração e é necessário fazer com que o CI seja aprovado. + +## Configurações de regras + +Algumas regras tem configurações. +Quando elas aceitam, você pode contorná-las ajustando o valor da regra de uma forma diferente. + +```json title="biome.json" +{ + "linter": { + "enabled": true, + "rules": { + "correctness": { + "noCommentText": { + "level": "warn", + "options": {} + } + } + } + } +} +``` + +- `level` indica a gravidade do diagnóstico, os valores válidos são: `"off"`, `"warn"` e `"error"`; +- `options` vai mudar dependendo da regra. diff --git a/website/src/content/docs/pt-br/recipes/continuous-integration.mdx b/website/src/content/docs/pt-br/recipes/continuous-integration.mdx new file mode 100644 index 000000000000..da6dcf151101 --- /dev/null +++ b/website/src/content/docs/pt-br/recipes/continuous-integration.mdx @@ -0,0 +1,32 @@ +--- +title: Integração Contínua +description: Usando Biome em um ambiente CI +--- + +Rodar o Biome em um ambiente CI é fácil. Dê uma olhada nos exemplos abaixo para ter uma inspiração. + +## GitHub Actions + +Nós fornecemos uma [GitHub Action](https://github.com/marketplace/actions/setup-biome) para configurar o Biome em seu ambiente de execução. +Aqui está como ficaria um simples Workflow: + +```yaml title="pull_request.yml" +name: Code quality + +on: + push: + pull_request: + +jobs: + quality: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Biome + uses: biomejs/setup-biome@v1 + with: + version: 1.2.2 + - name: Run Biome + run: biome ci . +``` diff --git a/website/src/content/docs/pt-br/reference/vscode.mdx b/website/src/content/docs/pt-br/reference/vscode.mdx new file mode 100644 index 000000000000..b280f57b6032 --- /dev/null +++ b/website/src/content/docs/pt-br/reference/vscode.mdx @@ -0,0 +1,141 @@ +--- +title: VSCode extension +description: Notes about the Biome's VSCode extension +--- +# Biome VS Code Extension + +[Biome](https://biomejs.dev/) unifies your development stack by combining the functionality of separate tools. It uses a single configuration file, has fantastic performance, and works with any stack. This extension brings Biome to your editor so that you can: + +- Format files *on save* or when issuing the *Format Document* command +- See lints while you type and apply code fixes +- Perform refactors + +## Installation + +You can install the code extension by heading to the extension's [Visual Studio Code Market Place page](https://marketplace.visualstudio.com/items?itemName=biomejs.biome) or from within VS Code by either: + +- Open the *extensions* tab (_View_ → _Extensions)_ and search for Biome. +- Open the _Quick Open Overlay_ (Ctrl/+P or _Go -> Go to File_), enter `ext install biomejs.biome`, and hit enter. + +## Getting Started + +### Default Formatter + +Configure Biome as the default formatter for supported files to ensure that VS Code uses Biome over other formatters that you may have installed. You can do so by opening a JavaScript or TypeScript and then: + +- Open the Command Palette (Ctrl/++P or View → Command Palette) +- Select _Format Document With…_ +- Select _Configure Default Formatter…_ +- Select Biome + +You can also enable Biome for specific languages only: + +- [Open the `settings.json`](https://code.visualstudio.com/docs/getstarted/settings#_settingsjson): open the _Command Palette_(Ctrl/++P) and select _Preferences: Open User Settings (JSON)_ +- And set the `editor.defaultFormatter` to `biomejs.biome` for the desired language + +```json title="settings.json" +{ + "editor.defaultFormatter": "", + "[javascript]": { + "editor.defaultFormatter": "biomejs.biome" + } +} +``` + +This configuration sets Biome as the default formatter for JavaScript files. All other files will be formatted using `` + +## Configuration Resolution + +The extension automatically loads the `biome.json` file from the workspace’s root directory. + +## Biome Resolution + +The extension tries to use Biome from your project's local dependencies (`node_modules/@biomejs/biome`). We recommend adding Biome as a project dependency to ensure that NPM scripts and the extension use the same Biome version. + +You can also explicitly specify the `Biome` binary the extension should use by configuring the `biome.lspBin` setting in your editor options. + +If the project has no dependency on Biome and no explicit path is configured, the extension uses the Biome version included in its bundle. + +## Usage + +### Format document + +To format an entire document, open the _Command Palette_ (Ctrl/++P) and select _Format Document_. + +To format a text range, select the text you want to format, open the _Command Palette_ (Ctrl/++P), and select _Format Selection_. + +### Format on save + +Biome respects VS Code's _Format on Save_ setting. To enable format on save, open the settings (_File_ -> _Preferences_ -> _Settings_), search for `editor.formatOnSave`, and enable the option. + +### Fix on save + +Biome respects VS Code's _Code Actions On Save_ setting. To enable fix on save, add + + +```json title="settings.json" +{ + "editor.codeActionsOnSave": { + "quickfix.biome": true + } +} +``` + +in vscode `settings.json`. + +### Imports Sorting [Experimental] + +The Biome VS Code extension supports imports sorting through the "Organize Imports" code action. By default this action can be run using the +Alt+O keyboard shortcut, or is accessible through the _Command Palette_ (Ctrl/++P) by selecting _Organize Imports_. + +You can add the following to your editor configuration if you want the action to run automatically on save instead of calling it manually: + +```json title="settings.json" +{ + "editor.codeActionsOnSave":{ + "source.organizeImports.biome": true + } +} +``` + +## Extension Settings + +### `biome.lspBin` + +The `biome.lspBin` option overrides the Biome binary used by the extension. +The workspace folder is used as the base path if the path is relative. + +### `biome.rename` + +Enables Biome to handle renames in the workspace (experimental). + +### `biome.requireConfiguration` + +Disables formatting, linting, and syntax errors for projects without a `biome.json` file. +Enabled by default. + +## Versioning + +We follow the specs suggested by [the official documentation](https://code.visualstudio.com/api/working-with-extensions/publishing-extension#prerelease-extensions): + +Odd minor versions are dedicated to pre-releases, e.g. `*.5.*` . +Even minor versions are dedicated to official releases, e.g. `*.6.*`. + + +## Troubleshooting + +> I installed `@biomejs/biome`, but the extension shows a warning saying that it could not resolve library. + +The library `@biomejs/biome` specifies some optional dependencies that are installed based on your OS and architecture. + +It's possible though, that the extension can't resolve the binary when loading the extension. This is caused - probably - by your package manager. + +**To resolve the issue**, try to install the binary manually. The warning should show you the binary that belongs to your machine. + +**If you work in a team that use different OSs/architectures**, it's advised to install all the binaries: + +- `@biomejs/cli-darwin-arm64` +- `@biomejs/cli-darwin-x64` +- `@biomejs/cli-linux-arm64` +- `@biomejs/cli-linux-x64` +- `@biomejs/cli-win32-arm64` +- `@biomejs/cli-win32-x64`