From aa2558d4d84e2ddc806d4e3fef4437ff540df858 Mon Sep 17 00:00:00 2001 From: Haoqun Jiang Date: Wed, 23 Aug 2023 11:30:34 +0800 Subject: [PATCH] fix: don't prettify if prettier 3 is detected --- docs/options.md | 2 +- docs/zh/options.md | 2 +- lib/loaders/templateLoader.js | 13 ++++++++++++- package.json | 3 +++ 4 files changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/options.md b/docs/options.md index 50e3346e0..6d82c9d89 100644 --- a/docs/options.md +++ b/docs/options.md @@ -90,7 +90,7 @@ When both options are specified, enables file-system-based template compilation ## prettify - type: `boolean` -- default: `true` +- default: `true` if prettier v1 or v2 is installed, `false` otherwise In development mode, we use [prettier](https://prettier.io/) to format the compiled render function for ease of debugging by default. However, if you encounter any obscure bug of prettier, such as [exponential compilation time for deeply nested functions](https://github.com/prettier/prettier/issues/4672), you can disable this option to circumvent it. diff --git a/docs/zh/options.md b/docs/zh/options.md index 8c904cbbe..e76bcc453 100644 --- a/docs/zh/options.md +++ b/docs/zh/options.md @@ -90,7 +90,7 @@ sidebar: auto ## prettify - 类型:`boolean` -- 默认值:`true` +- 默认值:当检测到 prettier v1 或 v2 时为 `true`,否则为 `false` 在开发环境下,我们默认使用 [prettier](https://prettier.io/) 格式化编译后的模板渲染代码,以方便调试。然而,如果你开发时碰到了 prettier 的某些罕见 bug,比如[格式化多层嵌套的函数时运行时间过长](https://github.com/prettier/prettier/issues/4672),你可以通过禁用这个选项来绕开。 diff --git a/lib/loaders/templateLoader.js b/lib/loaders/templateLoader.js index 0e8b0bbaf..b66c8420e 100644 --- a/lib/loaders/templateLoader.js +++ b/lib/loaders/templateLoader.js @@ -41,6 +41,17 @@ module.exports = function (source) { const descriptor = getDescriptor(filename, options, loaderContext) const script = resolveScript(descriptor, id, options, loaderContext) + // Prettier 3 APIs are all async + // but `vue/compiler-sfc` and `@vue/component-compiler-utils` can only use sync function to format code + let hasCompatiblePrettier = false + try { + const prettier = require('prettier/package.json') + const major = parseInt(prettier.version.split('.')[0], 10) + if (major === 1 || major === 2) { + hasCompatiblePrettier = true + } + } catch (e) {} + // for vue/compiler-sfc OR @vue/component-compiler-utils const finalOptions = { source, @@ -53,7 +64,7 @@ module.exports = function (source) { isProduction, isFunctional, optimizeSSR: isServer && options.optimizeSSR !== false, - prettify: options.prettify, + prettify: options.prettify === undefined ? hasCompatiblePrettier : options.prettify, bindings: script ? script.bindings : undefined } diff --git a/package.json b/package.json index 3e90c9a41..54be5cc2b 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,9 @@ }, "vue-template-compiler": { "optional": true + }, + "prettier": { + "optional": true } }, "dependencies": {