@134dd3v/prettier-plugin-solidity 中文文档教程
prettier-plugin-solidity
一个 Prettier 插件,用于自动格式化您的 Solidity 代码。
如果您喜欢这个项目,请考虑为我们的 Gitcoin grant 做贡献!
Installation and usage
安装 prettier
和 prettier-plugin-solidity
:
npm install --save-dev prettier prettier-plugin-solidity
在你的合约中运行 prettier:
npx prettier --write 'contracts/**/*.sol'
你可以添加一个脚本来在你的所有合约上运行 prettier:
"prettier": "prettier --write 'contracts/**/*.sol'"
或者你可以将它作为一部分使用检查你的所有代码是否经过美化:
"lint": "prettier --list-different 'contracts/**/*.sol'"
Who's using it?
这些是一些使用 Prettier Solidity 的项目:
Configuration File
Prettier 提供了一个灵活的系统来配置项目的格式化规则。 有关详细信息,请参阅文档。 以下是此插件内部使用的默认配置。
{
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 80,
"tabWidth": 4,
"useTabs": false,
"singleQuote": false,
"bracketSpacing": false,
"explicitTypes": "always"
}
}
]
}
请注意 overrides 属性 的使用,它允许在有其他语言的情况下进行多种配置项目(即 JavaScript、JSON、Markdown)。
Prettier 的文档 中描述了大多数选项。
Explicit Types
Solidity 分别为uint256
和int256
提供别名uint
和int
。 多个开发人员将有不同的编码风格,并且更喜欢一种风格。 添加此选项是为了标准化整个项目的代码,并强制使用一个别名而不是另一个别名。
有效选项:
"always"
: Prefer explicit types (uint256
,int256
, etc.)"never"
: Prefer type aliases (uint
,int
, etc.)."preserve"
: Respect the type used by the developer.
Default | CLI Override | API Override |
---|---|---|
"always" | --explicit-types <always|never|preserve> | explicitTypes: "<always|never|preserve>" |
// Input
uint public a;
int256 public b;
// "explicitTypes": "always"
uint256 public a;
int256 public b;
// "explicitTypes": "never"
uint public a;
int public b;
// "explicitTypes": "preserve"
uint public a;
int256 public b;
注意:如果提供了编译器选项且小于 0.8.0,则 explicitTypes 还将考虑显式类型 bytes1
的别名 byte
。
注意:在 uint
和 uint256
之间切换根本不会改变字节码,我们已经对此进行了测试。 但是,反映切换的 AST 会发生变化。
Compiler (experimental)
许多版本的 Solidity 编译器都有影响代码格式的更改。 默认情况下,此插件会尝试以尽可能兼容的方式格式化代码,但您可以使用实验性 compiler
选项将其推向正确的方向。
其中一个例子是导入指令。 在 0.7.4
之前,编译器不接受多行导入语句,因此我们总是将它们格式化为单行。 但是,如果您使用 compiler
选项来指示您使用的版本大于或等于 0.7.4
,则该插件将在有意义时使用多行导入。
格式化期间考虑的 solidity 版本是:
v0.7.4
: Versions prior0.7.4
had a bug that would not interpret correctly imports unless they are formatted in a single line.
// Input
import { Foo as Bar } from "/an/extremely/long/location";
// "compiler": undefined
import { Foo as Bar } from "/an/extremely/long/location";
// "compiler": "0.7.3" (or lesser)
import { Foo as Bar } from "/an/extremely/long/location";
// "compiler": "0.7.4" (or greater)
import {
Foo as Bar
} from "/an/extremely/long/location";
v0.8.0
:引入了这些 更改byte
类型已被删除。 它是bytes1
的别名。求幂是右结合的,即表达式
a**b**c
被解析为a**(b**c)
。 在0.8.0之前,它被解析为(a**b)**c
。
// Input
bytes1 public a;
byte public b;
uint public c = 1 ** 2 ** 3;
// "compiler": undefined
// "explicitTypes": "never"
bytes1 public a;
bytes1 public b;
uint public c = 1**2**3;
// "compiler": "0.7.6" (or lesser)
// "explicitTypes": "never"
byte public a;
byte public b;
uint public c = (1**2)**3;
// "compiler": "0.8.0" (or greater)
// "explicitTypes": "never"
bytes1 public a;
bytes1 public b;
uint public c = 1**(2**3);
您可能有一个多版本项目,其中不同的文件由不同的编译器编译。 如果是这种情况,您可以使用 overrides 进行更精细的配置:
{
"overrides": [
{
"files": "contracts/v1/**/*.sol",
"options": {
"compiler": "0.6.3"
}
},
{
"files": "contracts/v2/**/*.sol",
"options": {
"compiler": "0.8.4"
}
}
]
}
Default | CLI Override | API Override |
---|---|---|
None | --compiler <string> | compiler: "<string>" |
Integrations
Vim
要集成此插件使用 vim,首先安装 vim-prettier
。 这些 说明假设您正在使用 vim-plug
。 将此添加到您的配置中:
Plug 'prettier/vim-prettier', {
\ 'do': 'yarn install && yarn add prettier-plugin-solidity',
\ 'for': [
\ 'javascript',
\ 'typescript',
\ 'css',
\ 'less',
\ 'scss',
\ 'json',
\ 'graphql',
\ 'markdown',
\ 'vue',
\ 'lua',
\ 'php',
\ 'python',
\ 'ruby',
\ 'html',
\ 'swift',
\ 'solidity'] }
我们修改了 do
指令以同时安装此插件。 然后,您必须将插件配置为始终使用 安装在 vim 插件目录中的版本。 vim-plug 目录取决于您在 call plug#begin('~/.vim/
')
中使用的值:let g:prettier#exec_cmd_path = '~/.vim/plugged/vim-prettier/node_modules/.bin/prettier'
要检查一切是否正常,请打开一个 solidity 文件并运行 <代码>:更漂亮。
如果您还想在每次写入缓冲区时自动格式化,请添加以下行:
let g:prettier#autoformat = 0
autocmd BufWritePre *.sol Prettier
现在每次保存文件时都会运行 Prettier。
VSCode
VSCode 不熟悉 solidity 语言,因此需要 solidity
支持安装。
code --install-extension JuanBlanco.solidity
对于大多数情况,此扩展提供与 Prettier 的基本集成,无需进一步操作。
确保您的编辑器将保存时的格式设置为 true。 当你保存时,VSCode 会询问你想为 solidity 语言使用什么格式化程序,你可以选择 JuanBlanco.solidity
。
此时 VSCode 的 settings.json
应该有类似这样的配置:
{
"editor.formatOnSave": true,
"solidity.formatter": "prettier", // This is the default so it might be missing.
"[solidity]": {
"editor.defaultFormatter": "JuanBlanco.solidity"
}
}
如果你想更多地控制其他细节,你应该继续安装 prettier-vscode
。
code --install-extension esbenp.prettier-vscode
要与第 3 方插件交互,prettier-vscode
将查看项目的 npm 模块,因此您需要有 prettier
和 prettier-plugin-solidity< /code> 在你的
package.json
npm install --save-dev prettier prettier-plugin-solidity
这将允许你指定插件的版本,以防你想使用最新版本的插件或需要冻结格式,因为这个插件的新版本将对可能的格式进行调整。
您必须让 VSCode 使用您喜欢的格式化程序。 这可以通过打开命令面板并执行来完成:
>Preferences: Configure Language Specific Settings...
# Select Language
solidity
现在 VSCode 的 settings.json
应该有这个:
{
"editor.formatOnSave": true,
"[solidity]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
注意:根据设计,Prettier 优先考虑本地配置而不是全局配置。 如果你的项目中有一个 .prettierrc
文件,你的 VSCode 在 settings.json
中的默认设置或规则将被忽略(prettier/prettier-vscode#1079)。
Edge cases
Prettier Solidity 尽最大努力保持美观和一致,但在某些情况下,它会退回到做不太理想的事情。
Modifiers in constructors
没有参数的修饰符被格式化为删除了括号,构造函数除外。 这样做的原因是 Prettier Solidity 不能总是区分修饰符和基础构造函数。 所以构造函数中的修饰符没有被修改。 例如,此:
contract Foo is Bar {
constructor() Bar() modifier1 modifier2() modifier3(42) {}
function f() modifier1 modifier2() modifier3(42) {}
}
将被格式化为
contract Foo is Bar {
constructor() Bar() modifier1 modifier2() modifier3(42) {}
function f() modifier1 modifier2 modifier3(42) {}
}
注意 modifier2
中不必要的括号已在函数中删除,但未在构造函数中删除。
Contributing
- Fork it
- Create your feature branch (
git checkout -b feature/fooBar
) - Commit your changes (
git commit -am 'Add some fooBar'
) - All existing test and coverage must pass (
npm run test:all
), if coverage drops below 100% add missing tests. - Push to the branch (
git push origin feature/fooBar
) - Create a new Pull Request
License
在麻省理工学院许可下分发。 有关详细信息,请参阅许可证。
prettier-plugin-solidity
A Prettier plugin for automatically formatting your Solidity code.
If you like this project, please consider contributing to our Gitcoin grant!
Installation and usage
Install both prettier
and prettier-plugin-solidity
:
npm install --save-dev prettier prettier-plugin-solidity
Run prettier in your contracts:
npx prettier --write 'contracts/**/*.sol'
You can add a script for running prettier on all your contracts:
"prettier": "prettier --write 'contracts/**/*.sol'"
Or you can use it as part of your linting to check that all your code is prettified:
"lint": "prettier --list-different 'contracts/**/*.sol'"
Who's using it?
These are some of the projects using Prettier Solidity:
Configuration File
Prettier provides a flexible system to configure the formatting rules of a project. For more information please refer to the documentation. The following is the default configuration internally used by this plugin.
{
"overrides": [
{
"files": "*.sol",
"options": {
"printWidth": 80,
"tabWidth": 4,
"useTabs": false,
"singleQuote": false,
"bracketSpacing": false,
"explicitTypes": "always"
}
}
]
}
Note the use of the overrides property which allows for multiple configurations in case there are other languages in the project (i.e. JavaScript, JSON, Markdown).
Most options are described in Prettier's documentation.
Explicit Types
Solidity provides the aliases uint
and int
for uint256
and int256
respectively. Multiple developers will have different coding styles and prefer one over another. This option was added to standardize the code across a project and enforce the usage of one alias over another.
Valid options:
"always"
: Prefer explicit types (uint256
,int256
, etc.)"never"
: Prefer type aliases (uint
,int
, etc.)."preserve"
: Respect the type used by the developer.
Default | CLI Override | API Override |
---|---|---|
"always" | --explicit-types <always|never|preserve> | explicitTypes: "<always|never|preserve>" |
// Input
uint public a;
int256 public b;
// "explicitTypes": "always"
uint256 public a;
int256 public b;
// "explicitTypes": "never"
uint public a;
int public b;
// "explicitTypes": "preserve"
uint public a;
int256 public b;
Note: if the compiler option is provided and is lesser than 0.8.0, explicitTypes will also consider the alias byte
for the explicit type bytes1
.
Note: switching between uint
and uint256
does not alter the bytecode at all and we have implemented tests for this. However, there will be a change in the AST reflecting the switch.
Compiler (experimental)
Many versions of the Solidity compiler have changes that affect how the code should be formatted. This plugin, by default, tries to format the code in the most compatible way that it's possible, but you can use the experimental compiler
option to nudge it in the right direction.
One example of this are import directives. Before 0.7.4
, the compiler didn't accept multi-line import statements, so we always format them in a single line. But if you use the compiler
option to indicate that you are using a version greater or equal than 0.7.4
, the plugin will use multi-line imports when it makes sense.
The solidity versions taken into consideration during formatting are:
v0.7.4
: Versions prior0.7.4
had a bug that would not interpret correctly imports unless they are formatted in a single line.
// Input
import { Foo as Bar } from "/an/extremely/long/location";
// "compiler": undefined
import { Foo as Bar } from "/an/extremely/long/location";
// "compiler": "0.7.3" (or lesser)
import { Foo as Bar } from "/an/extremely/long/location";
// "compiler": "0.7.4" (or greater)
import {
Foo as Bar
} from "/an/extremely/long/location";
v0.8.0
: Introduced these changesThe type
byte
has been removed. It was an alias ofbytes1
.Exponentiation is right associative, i.e., the expression
a**b**c
is parsed asa**(b**c)
. Before 0.8.0, it was parsed as(a**b)**c
.
// Input
bytes1 public a;
byte public b;
uint public c = 1 ** 2 ** 3;
// "compiler": undefined
// "explicitTypes": "never"
bytes1 public a;
bytes1 public b;
uint public c = 1**2**3;
// "compiler": "0.7.6" (or lesser)
// "explicitTypes": "never"
byte public a;
byte public b;
uint public c = (1**2)**3;
// "compiler": "0.8.0" (or greater)
// "explicitTypes": "never"
bytes1 public a;
bytes1 public b;
uint public c = 1**(2**3);
You might have a multi-version project, where different files are compiled with different compilers. If that's the case, you can use overrides to have a more granular configuration:
{
"overrides": [
{
"files": "contracts/v1/**/*.sol",
"options": {
"compiler": "0.6.3"
}
},
{
"files": "contracts/v2/**/*.sol",
"options": {
"compiler": "0.8.4"
}
}
]
}
Default | CLI Override | API Override |
---|---|---|
None | --compiler <string> | compiler: "<string>" |
Integrations
Vim
To integrate this plugin with vim, first install vim-prettier
. These instructions assume you are using vim-plug
. Add this to your configuration:
Plug 'prettier/vim-prettier', {
\ 'do': 'yarn install && yarn add prettier-plugin-solidity',
\ 'for': [
\ 'javascript',
\ 'typescript',
\ 'css',
\ 'less',
\ 'scss',
\ 'json',
\ 'graphql',
\ 'markdown',
\ 'vue',
\ 'lua',
\ 'php',
\ 'python',
\ 'ruby',
\ 'html',
\ 'swift',
\ 'solidity'] }
We modified the do
instruction to also install this plugin. Then you'll have to configure the plugin to always use the version installed in the vim plugin's directory. The vim-plug directory depends on value you use in call plug#begin('~/.vim/<dir>')
:
let g:prettier#exec_cmd_path = '~/.vim/plugged/vim-prettier/node_modules/.bin/prettier'
To check that everything is working, open a solidity file and run :Prettier
.
If you also want to autoformat every time you write the buffer, add these lines:
let g:prettier#autoformat = 0
autocmd BufWritePre *.sol Prettier
Now Prettier will be run every time the file is saved.
VSCode
VSCode is not familiar with the solidity language, so solidity
support needs to be installed.
code --install-extension JuanBlanco.solidity
This extension provides basic integration with Prettier for most cases no further action is needed.
Make sure your editor has format on save set to true. When you save VSCode will ask you what formatter would you like to use for the solidity language, you can choose JuanBlanco.solidity
.
At this point VSCode's settings.json
should have a configuration similar to this:
{
"editor.formatOnSave": true,
"solidity.formatter": "prettier", // This is the default so it might be missing.
"[solidity]": {
"editor.defaultFormatter": "JuanBlanco.solidity"
}
}
If you want more control over other details, you should proceed to install prettier-vscode
.
code --install-extension esbenp.prettier-vscode
To interact with 3rd party plugins, prettier-vscode
will look in the project's npm modules, so you'll need to have prettier
and prettier-plugin-solidity
in your package.json
npm install --save-dev prettier prettier-plugin-solidity
This will allow you to specify the version of the plugin in case you want to use the latest version of the plugin or need to freeze the formatting since new versions of this plugin will implement tweaks on the possible formats.
You'll have to let VSCode what formatter you prefer. This can be done by opening the command palette and executing:
>Preferences: Configure Language Specific Settings...
# Select Language
solidity
Now VSCode's settings.json
should have this:
{
"editor.formatOnSave": true,
"[solidity]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
Note: By design, Prettier prioritizes a local over a global configuration. If you have a .prettierrc
file in your porject, your VSCode's default settings or rules in settings.json
are ignored (prettier/prettier-vscode#1079).
Edge cases
Prettier Solidity does its best to be pretty and consistent, but in some cases it falls back to doing things that are less than ideal.
Modifiers in constructors
Modifiers with no arguments are formatted with their parentheses removed, except for constructors. The reason for this is that Prettier Solidity cannot always tell apart a modifier from a base constructor. So modifiers in constructors are not modified. For example, this:
contract Foo is Bar {
constructor() Bar() modifier1 modifier2() modifier3(42) {}
function f() modifier1 modifier2() modifier3(42) {}
}
will be formatted as
contract Foo is Bar {
constructor() Bar() modifier1 modifier2() modifier3(42) {}
function f() modifier1 modifier2 modifier3(42) {}
}
Notice that the unnecessary parentheses in modifier2
were removed in the function but not in the constructor.
Contributing
- Fork it
- Create your feature branch (
git checkout -b feature/fooBar
) - Commit your changes (
git commit -am 'Add some fooBar'
) - All existing test and coverage must pass (
npm run test:all
), if coverage drops below 100% add missing tests. - Push to the branch (
git push origin feature/fooBar
) - Create a new Pull Request
License
Distributed under the MIT license. See LICENSE for more information.