Git Product home page Git Product logo

react-code-view's Introduction

React Code View

React Code View can render source code in markdown documents. And brings you the ability to render React components with editable source code and live preview.

React Code View

Install

npm install react-code-view

Configure Webpack

// webpack.config.js
export default {
  module: {
    rules: [
      {
        test: /\.md$/,
        loader: 'react-code-view/webpack-md-loader'
      }
    ]
  }
};

Options

{
  "parseLanguages": [
    // Supported languages for highlight.js
    // default: "javascript", "bash", "xml", "css", "markdown", "less", "typescript"
    // See https://github.com/highlightjs/highlight.js/blob/main/SUPPORTED_LANGUAGES.md
  ],
  "htmlOptions": {
    // HTML Loader options
    // See https://github.com/webpack-contrib/html-loader#options
  },
  "markedOptions": {
    // Pass options to marked
    // See https://marked.js.org/using_advanced#options
  }
}

webpack.config.js

export default {
  module: {
    rules: [
      {
        test: /\.md$/,
        use:[
          loader: 'react-code-view/webpack-md-loader',
          options:{
            parseLanguages: ['typescript','rust']
          }
        ]
      }
    ]
  }
};

Usage

import CodeView from 'react-code-view';
import { Button } from 'rsuite';

import 'react-code-view/styles/react-code-view.css';

return (
  <CodeView
    dependencies={{
      Button
    }}
  >
    {require('./example.md')}
  </CodeView>
);

The source code is written in markdown, refer to example.md

Note: The code to be rendered must be placed between <!--start-code--> and <!--end-code-->

Props

<CodeView>

Name Type Default value Description
afterCompile (code: string) => string Executed after compiling the code
beforeCompile (code: string) => string Executed before compiling the code
children any The code to be rendered is executed. Usually imported via markdown-loader
compileOptions object defaultTransformOptions https://github.com/alangpierce/sucrase#transforms
dependencies object Dependent objects required by the executed code
editable boolean false Renders a code editor that can modify the source code
editor object Editor properties
onChange (code?: string) => void Callback triggered after code change
onCloseEditor () => void Callback triggered when the editor is closed
onOpenEditor () => void Callback triggered when the editor is opened
renderExtraFooter () => ReactNode Customize the rendering footer
renderToolbar (buttons: ReactNode) => ReactNode Customize the rendering toolbar
sourceCode string The code to be rendered is executed
theme 'light' , 'dark' 'light' Code editor theme, applied to CodeMirror

react-code-view's People

Contributors

dependabot[bot] avatar hiyangguo avatar simonguo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-code-view's Issues

next.js 编译的时候会报错

版本信息:

  "next": "13.3.0",
  "react": "18.2.0",
  "react-code-view": "^2.2.1",
  "react-dom": "18.2.0",

在next.js 项目执行 build 命令时会报如下错误
image

报错代码:
image

组件渲染不出来 一直展示 Rendering...

platform: macos
node: 14.19.1
react: 18.2.0
react-dom: 18.2.0


next.config.js 配置

/* eslint-disable @typescript-eslint/no-require-imports */
/** @type {import('next').NextConfig} */

const { resolve } = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const resolvePath = dir => resolve(__dirname, dir)

const {
  // 'production' on main branch
  // 'preview' on pr branches
  // emtpy on local machine
  // @see https://vercel.com/docs/concepts/projects/environment-variables#system-environment-variables
  VERCEL_ENV = 'local'
} = process.env

const __DEV__ = VERCEL_ENV === 'preview' || VERCEL_ENV === 'local'

const nextConfig = {
  env: {
    DEV: __DEV__ ? 1 : 0
  },
  experimental: {
    externalDir: true
  },
  reactStrictMode: true,

  webpack(config) {
    config.module.rules.push({
      test: /\.(le|c)ss$/,
      use: [
        MiniCssExtractPlugin.loader,
        {
          loader: 'css-loader'
        },
        {
          loader: 'postcss-loader'
        },
        {
          loader: 'less-loader'
        }
      ]
    })

    config.module.rules.push({
      test: /\.md$/,
      use: [
        {
          loader: 'react-code-view/webpack-md-loader',
          options: {
            parseLanguages: ['typescript', 'rust', 'javascript']
          }
        }
      ]
    })

    config.plugins.push(
      new MiniCssExtractPlugin({
        experimentalUseImportModule: true, // isWebpack5
        filename: 'static/css/[name].css',
        chunkFilename: 'static/css/[contenthash].css'
      })
    )

    if (__DEV__) {
      Object.assign(config.resolve.alias, {
        'fortune-design': resolvePath('../src'),
        react: resolvePath('./node_modules/react'),
        'react-dom': resolvePath('./node_modules/react-dom')
      })
    }

    return config
  },
  // trailingSlash: true,
  // onDemandEntries: {
  //   // Period (in ms) where the server will keep pages in the buffer
  //   maxInactiveAge: 120 * 1e3, // default 25s
  //   // Number of pages that should be kept simultaneously without being disposed
  //   pagesBufferLength: 3 // default 2
  // },

  pageExtensions: ['tsx'],
  typescript: {
    tsconfigPath: __DEV__ ? './tsconfig.local.json' : './tsconfig.json'
  }
}

module.exports = nextConfig

Button.tsx

/* eslint-disable simple-import-sort/imports */
/* eslint-disable @typescript-eslint/no-require-imports */
import CodeView from 'react-code-view'
import 'react-code-view/styles/react-code-view.css'

const ButtonPage = () => {
  return (
    <div>
      <CodeView>{require('./button.md')}</CodeView>
    </div>
  )
}

export default ButtonPage

Button.md

image

展示效果:

image

ReferenceError: js is not defined

直接按readme操作(//cdn.staticfile.org/babel-standalone/6.24.0/babel.min.js 有正常加载到html的head),报错ReferenceError: js is not defined,怀疑是js的eval不识别:
image

CodeView 建议远程加载代码优化

现有代码使用

 export default class RedenvelopeTableList extends React.Component {

    public _CodeView: any

    public state = {
        code: 'const instance = <Button>Test</Button>;ReactDOM.render(instance);'
    }

    componentDidMount(): void {
         this._CodeView.executeCode(this.state.code)
    }

    public render() {
        return (
            <>
                <CodeView dependencies={{Button, Alert}} showCode={true}>{require('./example.md')}</CodeView>
                <CodeView ref={ref => this._CodeView = ref} dependencies={{Button, Alert}} showCode={true}/>
            </>

        )
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.