UNPKG

2.71 kBMarkdownView Raw
1# mdx-scoped-runtime
2
3[![npm version][version-badge]][version]
4[![Build Status][build-badge]][build]
5[![License: MIT][license-badge]][license]
6[![module formats: cjs][module-formats-badge]][unpkg-bundle]
7
8This is a wrapper around [`mdx-runtime`][mdx-runtime] that strips down the `import ...`
9and `export default Layout` out of the MDX at runtime.
10
11## Install
12
13```shell
14npm i mdx-scoped-runtime
15```
16
17## How to use
18
19You can provide any instances to the scope without any validation of the import path:
20
21```js
22import React from 'react';
23import MDX from 'mdx-scoped-runtime';
24import * as UI from '../components';
25import Layout from '../ui/Layout';
26
27// Provide custom components for markdown elements
28const components = {
29 h1: props => <h1 style={{ color: 'tomato' }} {...props} />,
30};
31
32// Provide custom components that will be referenced as JSX
33// in the markdown string
34const scope = {
35 ...UI,
36 Demo: props => <h1>This is a demo component</h1>,
37};
38
39const mdx = `
40import Layout from '../ui/Layout';
41import { Calendar } from '../components';
42import Demo from 'wherever';
43
44export default Layout
45
46# Hello, world!
47
48<Calendar />
49
50<Demo />
51`;
52
53export default () => (
54 <MDX components={components} scope={scope}>
55 {mdx}
56 </MDX>
57);
58```
59
60### Advanced usage
61
62You can validate the imports via `allowedImports` prop:
63
64```js
65import React from 'react';
66import MDX from 'mdx-scoped-runtime';
67import * as UI from '../components';
68import Layout from '../ui/Layout';
69
70const scope = {
71 // scope can still be used in combination with allowedImports
72};
73
74const mdx = `
75import Layout from '../ui/Layout';
76import { Calendar } from '../components';
77import Demo from 'wherever';
78
79export default Layout
80
81# Hello, world!
82
83<Calendar />
84
85<Demo />
86`;
87
88const allowedImports = {
89 wherever: {
90 ImportDefault: props => <h1>This is a demo component</h1>,
91 },
92 '../ui/Layout': {
93 ImportDefault: Layout,
94 },
95 '../components': {
96 Import: UI,
97 },
98};
99
100export default () => (
101 <MDX
102 components={components}
103 scope={scope}
104 allowedImports={allowedImports}
105 onError={error => console.log(error)}
106 >
107 {mdx}
108 </MDX>
109);
110```
111
112## License
113
114MIT
115
116[version-badge]: https://badge.fury.io/js/mdx-scoped-runtime.svg
117[version]: https://www.npmjs.com/package/mdx-scoped-runtime
118[build-badge]: https://travis-ci.org/karolis-sh/gatsby-mdx.svg?branch=master
119[build]: https://travis-ci.org/karolis-sh/gatsby-mdx
120[license-badge]: https://img.shields.io/badge/License-MIT-yellow.svg
121[license]: https://opensource.org/licenses/MIT
122[mdx-runtime]: https://www.npmjs.com/package/@mdx-js/runtime
123[module-formats-badge]: https://img.shields.io/badge/module%20formats-cjs-green.svg
124[unpkg-bundle]: https://unpkg.com/mdx-scoped-runtime/