You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pnpm+prettier-plugin-tailwindcss时VSCode Prettier扩展失效求助

问题描述

为了对TailwindCSS类进行排序,我使用prettier-plugin-tailwindcss插件,项目采用pnpm包管理器,根目录添加了prettier.config.cjs配置文件。项目为TypeScript类型,package.json中包含"type": "module"配置,prettier版本为2.8.8,VSCode的Prettier扩展版本是v9.15.0。

目前遇到两个错误:

  1. 编辑器中prettier.config.cjs文件出现报错
  2. 保存任意文件时触发格式化错误,报错信息如下:
["ERROR" - 20:13:52] Error formatting document.
["ERROR" - 20:13:52] parse(a,m,f={}){let{context:s,generateRules:l}=dI(f),c=Wm(ws,e,f);c.astFormat in vv&&(f.printer=vv[c.astFormat]...<omitted>...d} could not be cloned.
DataCloneError: parse(a,m,f={}){let{context:s,generateRules:l}=dI(f),c=Wm(ws,e,f);c.astFormat in vv&&(f.printer=vv[c.astFormat]...<omitted>...d} could not be cloned.
    at new DOMException (node:internal/per_context/domexception:72:5)
    at Worker.postMessage (node:internal/worker:343:5)
    at t.PrettierWorkerInstance.callMethod (/home/rajbharti/.vscode-oss/extensions/esbenp.prettier-vscode-9.15.0/dist/extension.js:1:17460)
    at t.PrettierWorkerInstance.format (/home/rajbharti/.vscode-oss/extensions/esbenp.prettier-vscode-9.15.0/dist/extension.js:1:17078)
    at t.default.format (/home/rajbharti/.vscode-oss/extensions/esbenp.prettier-vscode-9.15.0/dist/extension.js:1:14808)
    at async t.PrettierEditProvider.provideEdits (/home/rajbharti/.vscode-oss/extensions/esbenp.prettier-vscode-9.15.0/dist/extension.js:1:11430)
    at async N.provideDocumentFormattingEdits (/usr/share/codium/resources/app/out/vs/workbench/api/node/extensionHostProcess.js:101:52602)
["INFO" - 20:13:52] Formatting completed in 11ms.

已尝试的解决方法:

  • 将配置文件从prettier.config.js重命名为prettier.config.cjs,解决了ES模块错误
  • 在prettier.config.cjs中添加/* eslint-disable no-undef */,但保存文件时的格式化错误仍未解决
解决方案

1. 修复prettier.config.cjs编辑器报错

由于项目开启了"type": "module",VSCode可能误将.cjs文件识别为ES模块,导致语法报错。可通过以下方式解决:

  • 在配置文件顶部添加环境注释,明确告知ESLint这是Node环境:
    /* eslint-env node */
    module.exports = {
      plugins: ['prettier-plugin-tailwindcss'],
      // 其他Prettier配置项
    }
    
  • 若仍有报错,修改VSCode的files.associations设置,确保.cjs文件被识别为CommonJS:
    打开VSCode设置(快捷键Ctrl+,),添加如下配置:
    "files.associations": {
      "*.cjs": "javascript"
    }
    

2. 解决保存时的DataCloneError格式化错误

该错误多由Prettier版本、插件版本、VSCode扩展三者不兼容导致,可按以下步骤排查:

  • 匹配插件与Prettier版本:prettier-plugin-tailwindcss对Prettier版本有明确要求,针对Prettier 2.8.8,需安装^0.2.0区间的插件。执行命令安装适配版本:
    pnpm add -D prettier-plugin-tailwindcss@0.2.8
    
  • 强制VSCode使用项目本地Prettier:默认情况下,VSCode扩展可能自带Prettier版本,与项目本地版本冲突。修改VSCode设置:
    "prettier.resolveGlobalModules": false,
    "prettier.prettierPath": "./node_modules/prettier"
    
  • 重启VSCode生效:修改配置后,通过快捷键Ctrl+Shift+P选择"Reload Window"重启窗口,确保配置完全生效。

内容的提问来源于stack exchange,提问作者Raj Kumar Bharti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 05:17:29