Prettier 內建已經支援 Vue,但只支援 .vue
,但 Petite-vue 通常會搭配後端或 SSG,如 Hugo 只支援 .html
,若要使用 Prettier 在其他副檔名,則必須在 .prettierrc
做額外設定。
Version
WebStorm 2023.3.3
Prettier 3.2.2
Petite-vue 0.41
Install Prettier
$ npm install -D prettier
- 使用 NPM 安裝 Prettier
Configuration
.prettierrc
{
"htmlWhitespaceSensitivity": "ignore",
"semi": false,
"singleQuote": true,
"arrowParens": "avoid",
"overrides": [
{
"files": ["*.htm", "*.html"],
"options": {
"parser": "vue"
}
}
]
}
Line 2
"htmlWhitespaceSensitivity": "ignore",
"semi": false,
"singleQuote": true,
"arrowParens": "avoid",
htmlWhitespaceSensitivity: ignore
:HTML 忽略 white space 不換行semi: false
:JavaScript 支援 ASI,結尾不加分號singleQuote: true
:JavaScript 的 String 使用單引號,但 HTML 與 CSS 仍維持雙引號arrowParens: avoid
:JavaScript 的 function 只有一個參數時不加()
Line 6
"overrides": [
{
"files": ["*.htm", "*.html"],
"options": {
"parser": "vue"
}
}
]
.htm
與.html
視為.vue
處理
WebStorm
Settings -> Languages & Frameworks -> JavaScript -> Prettier
- Manual Prettier configuration
- Prettier package:指定
node_modules
下的prettier
- Run on Reformat Code action:
On
- Run for files:
**/*.{htm, html}
- Run on save:
On
- Prettier package:指定
Petite-vue
index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Petite-vue Lab</title>
</head>
<body>
<div>
<button @click="onClick">+</button>
<div>{{ states.count }}</div>
</div>
</body>
</html>
<script type="module">
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
let states = reactive({
count: 0
})
let onClick = () => states.count++
createApp({
states,
onClick
}).mount()
</script>
Line 16
<script type="module">
import { createApp, reactive } from 'https://unpkg.com/petite-vue?module'
let states = reactive({
count: 0
})
let onClick = () => states.count++
createApp({
states,
onClick
}).mount()
</script>
- 將
.html
視為.vue
之後,可發現<script>
之內不再向內縮排,如此符合 Vue 的習慣
Conclusion
- Prettier 已經內建支援 Vue,只可惜 Petite-vue 通常不會使用
.vue
為副檔名,因此必須在.prettierrc
做額外設定