jsx-to-string webpack loader
Easily convert code between delimiters to string. Pairs well with projects like react-live and react-simple-code-editor.
Installation
yarn add jsx-to-string-loader --dev
or
npm install jsx-to-string-loader --save-dev
Configuration
Add loader to webpack.config.js
Example:
module: rules: test: /\.jsx$/ use: loader: 'jsx-to-string-loader' ;
Make sure jsx-to-string-loader
comes after loaders such as babel-loader
or ts-loader
.
Usage
Usage example with react-simple-code-editor
import Editor from 'react-simple-code-editor'; const code = /* jsx-to-string:start */ <strong>Hello World!</strong> /* jsx-to-string:end */; { return <Editor = />;}
Will be transformed to:
; const code = `<strong>Hello World!</strong>`; { return <Editor code=code />;}
The idea is that you keep writing JSX instead of template strings. It makes more sense when writing more involved components. This next one is using react-live to show an example of a component with state.
import React useState from 'react';import LiveProvider LiveEditor LiveError LivePreview from 'react-live'; const exampleCode = /* jsx-to-string:start */ { const count setCount = ; return <div> <p>You clicked count times</p> <button =>Click me</button> </div> ; } /* jsx-to-string:end */; const scope = useState ; { return <LiveProvider = => <LiveEditor /> <LiveError /> <LivePreview /> </LiveProvider> ;}
You can also use it inside of JSX
{ return <Example> <div> <p>Hello world</p> </div> </Example> ;}
Will be transformed to:
{ return <Example>`<div> <p>Hello world</p></div>` </Example> ;}