Pretier web使用情况



我尝试用react应用程序格式化输入文本。我在这里试图实现的是,这个组件从道具中获得文本输入,它通过所需的";translator";函数,并将翻译后的代码写在右侧。我希望这个新的文本const newInput = string通过更漂亮的格式。Prettier正在web上工作,所以应该没什么大不了的,但当我尝试使用Prettier.format((函数时,它就不起作用了。

我看不到任何不能在React中使用的东西,但它仍然不起作用,并表示它无法解决进口问题,这可以在React组件的顶部看到。那么我该如何暗示这一点或格式化任何输入文本的任何其他建议;"更漂亮";喜欢

这是此功能的原始文档:

<script type="text/javascript">
var formatButton = document.querySelector("#format");
var textInput = document.querySelector("#input");
formatButton.addEventListener("click", function() {
var value = textInput.value;
textInput.value = prettier.format(value, {
parser: "babylon",
plugins: prettierPlugins
});
});
</script>

这是我迄今为止的代码:

import React from "react";
//prettier imports
import prettier from "https://unpkg.com/prettier@2.2.1/esm/standalone.mjs";
import parserBabel from "https://unpkg.com/prettier@2.2.1/esm/parser-babel.mjs";
import parserHtml from "https://unpkg.com/prettier@2.2.1/esm/parser-html.mjs";
const Display = (props) => {
const { input, isToggled } = props;
// entity to HTML
const tagsToReplace = {
"&": "&amp;",
"&lt;": "<",
"&gt;": ">",
"&nbsp;": " ",
};
const newInput = input.toString().replace(/&lt;|&gt;/gi, function (matched) {
return tagsToReplace[matched];
});
//HTML to entity
const tagsToReplaceBack = {
"<": "&lt;",
">": "&gt;",
};
const changeBackInput = input.toString().replace(/<|>/gi, function (matched) {
return tagsToReplaceBack[matched];
});
const formattedInput = prettier.format(newInput, {
parser: "babel",
plugins: [parserBabel, parserHtml],
});

return <div>{formattedInput}</div>;
};
export default Display;
/* {isToggled ? <div>{changeBackInput}</div> : <div>{newInput}</div>} */

我认为您的bundler(可能是webpack?(不支持从URL导入模块。您需要从npm安装Prettier作为依赖项,并以导入React的方式导入它。例如,请参阅此Codesandbox:https://codesandbox.io/s/async-worker-2oul0?file=/src/App.js

相关内容

最新更新