jsx-to-string-loader
TypeScript icon, indicating that this package has built-in type declarations

1.2.0 • Public • Published

jsx-to-string webpack loader

npm version Build status

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 */
);
 
function App() {
  return <Editor value={code} />;
}

Will be transformed to:

import Editor from 'react-simple-code-editor';
 
const code = `<strong>Hello World!</strong>`;
 
function App() {
  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 */
  function Example() {
    const [count, setCount] = useState(0);
 
    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>Click me</button>
      </div>
    );
  }
  /* jsx-to-string:end */
);
 
const scope = { useState };
 
function App() {
  return (
    <LiveProvider code={code} scope={scope}>
      <LiveEditor />
      <LiveError />
      <LivePreview />
    </LiveProvider>
  );
}

You can also use it inside of JSX

function App() {
  return (
    <Example>
      <div>
        <p>Hello world</p>
      </div>
    </Example>
  );
}

Will be transformed to:

function App() {
  return (
    <Example>
{`<div>
  <p>Hello world</p>
</div>`}
    </Example>
  );
}

Readme

Keywords

none

Package Sidebar

Install

npm i jsx-to-string-loader

Weekly Downloads

49

Version

1.2.0

License

MIT

Unpacked Size

9.68 kB

Total Files

9

Last publish

Collaborators

  • deini