mdx-scoped-runtime

0.8.0 • Public • Published

mdx-scoped-runtime

npm version Build Status License: MIT module formats: cjs

This is a wrapper around mdx-runtime that strips down the import ... and export default Layout out of the MDX at runtime.

Install

npm i mdx-scoped-runtime

How to use

You can provide any instances to the scope without any validation of the import path:

import React from 'react';
import MDX from 'mdx-scoped-runtime';
import * as UI from '../components';
import Layout from '../ui/Layout';

// Provide custom components for markdown elements
const components = {
  h1: (props) => <h1 style={{ color: 'tomato' }} {...props} />,
};

// Provide custom components that will be referenced as JSX
// in the markdown string
const scope = {
  ...UI,
  Demo: (props) => <h1>This is a demo component</h1>,
};

const mdx = `
import Layout from '../ui/Layout';
import { Calendar } from '../components';
import Demo from 'wherever';

export default Layout

# Hello, world!

<Calendar />

<Demo />
`;

export default () => (
  <MDX components={components} scope={scope}>
    {mdx}
  </MDX>
);

Advanced usage

You can validate the imports via allowedImports prop:

import React from 'react';
import MDX from 'mdx-scoped-runtime';
import * as UI from '../components';
import Layout from '../ui/Layout';

const scope = {
  // scope can still be used in combination with allowedImports
};

const mdx = `
import Layout from '../ui/Layout';
import { Calendar } from '../components';
import Demo from 'wherever';

export default Layout

# Hello, world!

<Calendar />

<Demo />
`;

const allowedImports = {
  wherever: {
    ImportDefault: (props) => <h1>This is a demo component</h1>,
  },
  '../ui/Layout': {
    ImportDefault: Layout,
  },
  '../components': {
    Import: UI,
  },
};

export default () => (
  <MDX
    components={components}
    scope={scope}
    allowedImports={allowedImports}
    onError={(error) => console.log(error)}
  >
    {mdx}
  </MDX>
);

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i mdx-scoped-runtime

Weekly Downloads

30

Version

0.8.0

License

MIT

Unpacked Size

54.6 kB

Total Files

20

Last publish

Collaborators

  • karolis.sarapnickis