React中Monaco Editor集成Prettier格式化报错:TypeError读取'languages'失败
解决Prettier standalone集成时的"Cannot read properties of undefined (reading 'languages')"错误
问题场景
在React项目中基于Monaco Editor构建代码编辑器,尝试集成Prettier实现代码格式化功能时,出现以下错误:TypeError: Cannot read properties of undefined (reading 'languages') at standalone.mjs:22:694
原代码如下:
import parser from "prettier/parser-babel"; try { const test = async () => { const code = `function add(a, b) { return a + b; }`; const prettier = await import("prettier/standalone"); const formattedCode = await prettier.format(code, { semi: true, parser: "babel", plugins: [parser], useTabs: false, }); console.log({ formattedCode }); }; test(); } catch (e) { console.log({ e }); }
更换不同parser后问题仍未解决。
解决方案
1. 确保Prettier核心与parser版本完全一致
这个错误大多源于Prettier主包和对应的parser包版本不匹配。
- 打开
package.json,检查prettier和prettier/parser-babel的版本号,必须保持相同 - 重新安装匹配版本:
npm install prettier@latest prettier/parser-babel@latest # 或使用yarn yarn add prettier@latest prettier/parser-babel@latest
2. 调整动态导入方式,同步加载prettier和parser
原代码中提前导入parser,可能导致加载顺序问题,改为同时动态导入两者:
try { const test = async () => { const code = `function add(a, b) { return a + b; }`; // 并行动态导入prettier和parser const [prettier, { default: parser }] = await Promise.all([ import("prettier/standalone"), import("prettier/parser-babel") ]); const formattedCode = prettier.format(code, { semi: true, parser: "babel", plugins: [parser], useTabs: false, }); console.log({ formattedCode }); }; test(); } catch (e) { console.log({ e }); }
3. 禁用Tree Shaking(可选)
部分打包工具(如Webpack)的Tree Shaking可能误删Prettier的必要代码,可在配置中关闭:
// webpack.config.js module.exports = { optimization: { usedExports: false, }, };
内容的提问来源于stack exchange,提问作者Sanjoy Pator
相关产品推荐
相关产品推荐

