Reputation: 111
I try to format an imput text with a react app. What I'm trying to achieve here is, this component gets a text input from props, it goes through the needed "traslator" functions, and writes the translated code on the right. I'd like this new text const newInput = string
to be formatted via prettier. Prettier is working on web so it should be no biggie, but when I try to use the prettier.format() function it won't work.
I can't see anything that could not be used in React, but it still won't work and says that it cant resolve the imports, which can be seen on the top of the react component. so how could I implent this, or any other advice for formatting any input text "prettier" like?
This is the original documentation for this funcion:
<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>
This is my code so far:
import React from "react";
//prettier imports
import prettier from "https://unpkg.com/[email protected]/esm/standalone.mjs";
import parserBabel from "https://unpkg.com/[email protected]/esm/parser-babel.mjs";
import parserHtml from "https://unpkg.com/[email protected]/esm/parser-html.mjs";
const Display = (props) => {
const { input, isToggled } = props;
// entity to HTML
const tagsToReplace = {
"&": "&",
"<": "<",
">": ">",
" ": " ",
};
const newInput = input.toString().replace(/<|>/gi, function (matched) {
return tagsToReplace[matched];
});
//HTML to entity
const tagsToReplaceBack = {
"<": "<",
">": ">",
};
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>} */
Upvotes: 0
Views: 765
Reputation: 10427
I think your bundler (webpack, probably?) doesn't support importing modules from URLs. You need to install Prettier from npm as a dependency and import it the same way you import React. E.g. see this Codesandbox: https://codesandbox.io/s/async-worker-2oul0?file=/src/App.js
Upvotes: 1