Han*_*ney 1 google-code-prettify reactjs js-beautify react-ace
我研究了代码美化器,如 google-code-prettify、beautify 等。不幸的是,我无法让这些在我的 React 应用程序中工作。我目前正在使用react-ace来显示动态填充的代码片段,但它们只是颜色突出显示,而不是格式化。
有没有一些简单的例子可以让我在 React 应用程序中使用它?它不必使用 Ace 编辑器 - 这是我的一种技巧,可以让代码显示得更好。
Yas*_*shi 11
感谢您提出这个问题,您可以使用 prettier 来格式化代码。您可能需要根据您使用的语言或框架配置不同的解析器。
这是一个用于格式化 JS 代码的示例codesandbox。链接:https ://codesandbox.io/s/currying-architecture-tm785?file=/src/App.js
主文件代码:
import React from "react";
import prettier from "prettier/standalone";
import babylon from "prettier/parser-babel";
import "./styles.css";
export default function App() {
const [code, setCode] = React.useState(`
const a = "abc";
const b = 'a'
console.log(a);
`);
const formatCode = () => {
const formattedCode = prettier.format(code, {
parser: "babel",
plugins: [babylon]
});
setCode(formattedCode);
};
return (
<div className="App">
<textarea
style={{ height: "100px", width: "100%", display: "block" }}
value={code}
/>
<button onClick={formatCode}>Format Code with Prettier</button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
4157 次 |
| 最近记录: |