Skip to content

Commit 3c6c9dd

Browse files
committed
feat: add prettier to monaco
1 parent 6d606a3 commit 3c6c9dd

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/monaco/Monaco.vue

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@ import { getOrCreateModel } from './utils'
1616
import { loadGrammars, loadTheme } from 'monaco-volar'
1717
import { Store } from '../store'
1818
import type { PreviewMode } from '../editor/types'
19+
import parserBabel from 'prettier/parser-babel'
20+
import parserHtml from 'prettier/parser-html'
21+
import parserPostcss from 'prettier/parser-postcss'
22+
import prettier from 'prettier/standalone'
1923
2024
const props = withDefaults(
2125
defineProps<{
@@ -41,6 +45,7 @@ const store = inject<Store>('store')!
4145
initMonaco(store)
4246
4347
const lang = computed(() => (props.mode === 'css' ? 'css' : 'javascript'))
48+
const extension = computed(() => props.filename.split('.').at(-1))
4449
4550
const replTheme = inject<Ref<'dark' | 'light'>>('theme')!
4651
onMounted(async () => {
@@ -146,6 +151,31 @@ onMounted(async () => {
146151
emit('change', editorInstance.getValue())
147152
})
148153
154+
editorInstance.onDidBlurEditorWidget(() => {
155+
const parser = {
156+
vue: 'html',
157+
html: 'html',
158+
css: 'css',
159+
js: 'babel',
160+
ts: 'babel',
161+
}[extension.value] || props.mode
162+
163+
const options = {
164+
parser,
165+
plugins: [parserBabel, parserHtml, parserPostcss],
166+
semi: false,
167+
singleQuote: true,
168+
arrowParens: 'avoid' as const,
169+
}
170+
171+
let code = editorInstance.getValue()
172+
try {
173+
code = prettier.format(code, options)
174+
} catch (err) {}
175+
176+
emit('change', code)
177+
})
178+
149179
// update theme
150180
watch(replTheme, (n) => {
151181
editorInstance.updateOptions({

0 commit comments

Comments
 (0)