Code Monkey home page Code Monkey logo

remark-mdx-code-meta's Introduction

remark-mdx-code-meta

github actions npm prettier codecov

A remark MDX plugin for using markdown code block metadata

Warning This package has been deprecated. Use rehype-mdx-code-props instead.

Installation

npm install remark-mdx-code-meta

Usage

This plugin interprets markdown code block metadata as JSX props.

For example, given a file named example.mdx with the following contents:

```js copy filename="awesome.js" onUsage={props.beAwesome} {...props}
console.log('Everything is awesome!');
```

The following script:

import { readFileSync } from 'fs';

import remarkMdxCodeMeta from 'remark-mdx-code-meta';
import { compileSync } from 'xdm';

const { contents } = compileSync(readFileSync('example.mdx'), {
  jsx: true,
  remarkPlugins: [remarkMdxCodeMeta],
});
console.log(contents);

Roughly yields:

export default function MDXContent(props) {
  return (
    <pre copy filename="awesome.js" onUsage={props.beAwesome} {...props}>
      <code className="language-js">{"console.log('Everything is awesome!');\n"}</code>
    </pre>
  );
}

Of course the <pre /> element doesn’t support those custom props. Use custom [components][] to give the props meaning.

License

MIT @ Remco Haszing

remark-mdx-code-meta's People

Contributors

lachlanjc avatar remcohaszing 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

Watchers

 avatar  avatar  avatar

remark-mdx-code-meta's Issues

Does this need XDM?

I am trying it on my Next.js app β†’ https://github.com/deadcoder0904/better-code-blocks but I'm getting an error:

./src/pages/tutorial/better-code-blocks/index.mdx
SyntaxError: JSX value should be either an expression or a quoted JSX text (1:11)

next.config.js

const path = require('path')
const { createLoader } = require('simple-functional-loader')
const visit = require('unist-util-visit')
const withBundleAnalyzer = require('@next/bundle-analyzer')({
	enabled: process.env.ANALYZE === 'true',
})
const { remarkMdxCodeMeta } = require('remark-mdx-code-meta')

const rehypeHighlightCode = require('./rehype/highlight-code')
const rehypeMetaAttribute = require('./rehype/meta-attribute')
// const { withSyntaxHighlighting } = require('./remark/withSyntaxHighlighting')
// const withCodeSamples = require('./remark/withCodeSamples')

module.exports = withBundleAnalyzer({
	future: {
		webpack5: true,
	},
	pageExtensions: ['js', 'jsx', 'ts', 'tsx', 'md', 'mdx'],
	experimental: {
		modern: true,
	},
	redirects: async () => {
		return require('./redirects.json')
	},
	webpack: (config, options) => {
		config.module.rules.push({
			test: /\.(svg|png|jpe?g|gif|mp4)$/i,
			use: [
				{
					loader: 'file-loader',
					options: {
						publicPath: '/_next',
						name: 'static/media/[name].[hash].[ext]',
					},
				},
			],
		})

		const mdx = [
			options.defaultLoaders.babel,
			{
				loader: '@mdx-js/loader',
				options: {
					remarkPlugins: [
						/*withCodeSamples, withSyntaxHighlighting*/
						remarkMdxCodeMeta,
					],
					rehypePlugins: [rehypeMetaAttribute, rehypeHighlightCode],
				},
			},
		]

		config.module.rules.push({
			test: /\.mdx$/,
			oneOf: [
				{
					resourceQuery: /preview/,
					use: [
						...mdx,
						createLoader(function (src) {
							if (src.includes('<!-- more -->')) {
								const [preview] = src.split('<!-- more -->')
								return this.callback(null, preview)
							}

							const [preview] = src.split('<!--/excerpt-->')
							return this.callback(null, preview.replace('<!--excerpt-->', ''))
						}),
					],
				},
				{
					resourceQuery: /rss/,
					use: [
						...mdx,
						createLoader(function (src) {
							return this.callback(null, src)
						}),
					],
				},
				{
					include: [path.resolve(__dirname, 'src/pages/essay')],
					use: [
						...mdx,
						createLoader(function (src) {
							const content = [
								'import Essay from "@/components/Essay"',
								'export { getStaticProps } from "@/utils/essay/getStaticProps"',
								src,
								'export default (props) => <Essay meta={meta} {...props} />',
							].join('\n')

							if (content.includes('<!-- more -->')) {
								return this.callback(null, content.split('<!-- more -->').join('\n'))
							}

							return this.callback(null, content.replace(/<!--excerpt-->.*<!--\/excerpt-->/s, ''))
						}),
					],
				},
				{
					include: [path.resolve(__dirname, 'src/pages/tutorial')],
					use: [
						...mdx,
						createLoader(function (src) {
							const content = [
								'import Tutorial from "@/components/Tutorial"',
								'export { getStaticProps } from "@/utils/tutorial/getStaticProps"',
								src,
								'export default (props) => <Tutorial meta={meta} {...props} />',
							].join('\n')

							if (content.includes('<!-- more -->')) {
								return this.callback(null, content.split('<!-- more -->').join('\n'))
							}

							return this.callback(null, content.replace(/<!--excerpt-->.*<!--\/excerpt-->/s, ''))
						}),
					],
				},
			],
		})

		if (!options.dev && options.isServer) {
			const originalEntry = config.entry

			config.entry = async () => {
				const entries = { ...(await originalEntry()) }
				entries['./scripts/build-rss'] = './scripts/build-rss.js'
				entries['./scripts/build-sitemap'] = './scripts/build-sitemap.js'
				return entries
			}
		}

		return config
	},
})

Broken README example

Version 2.0.0 README example:

import { remarkMdxCodeMeta } from "remark-mdx-code-meta";

fails with:

SyntaxError: The requested module 'remark-mdx-code-meta' does not provide an export named 'remarkMdxCodeMeta'

Solution:

import remarkMdxCodeMeta from "remark-mdx-code-meta";

Is there a way to use this with rehype-highlight?

Hi there,
Thanks for this, it works great for passing down the metadata as props, but I have hit a problem: It breaks syntax highlighting with rehype-highlight.

import { compile } from '@mdx-js/mdx'
import codeMeta from 'remark-mdx-code-meta'
import rehypeHighlight from 'rehype-highlight'

compile(md, {
  outputFormat: 'function-body',
  remarkPlugins: [
    codeMeta, // adding this breaks syntax highlighting
  ],
  rehypePlugins: [
    [rehypeHighlight, { plainText: ['http'] }],
  ]
})

Result with your plugin:
Screenshot from 2022-10-05 04-17-24

Result without your plugin:
Screenshot from 2022-10-05 04-16-48

If you had any pointers on how to make this plugin play nice with rehype-highlight I would very much appreciate hearing about them πŸ™

thank you
joost

Still supported? Can't get it to work with XDM and webpack

Hi there,

Thanks for the package!

I'm currently trying to make this work with a custom react webpack setup to expose meta data on code blocks.

This is what my webpack config looks like:

const codeMeta = require('remark-mdx-code-meta');

[...]
      {
        test: /\.mdx?$/,
        use: [
          {
            loader: 'xdm/webpack.cjs',
            options: {
              providerImportSource: '@mdx-js/react',
              remarkPlugins: [codeMeta.remarkMdxCodeMeta],
            },
          },
        ],
      },
[...]

While it compiles, I can't seem to get the actual plugin to work.

This is my React file:

import React from 'react'
import { MDXProvider } from '@mdx-js/react';
import Test from './test.mdx'

const components = {
  code: (p) => {
    console.log(p);
    return <div />
  }
}

export const Preview = () => (
  <MDXProvider components={components}>
    <Test />
  </MDXProvider>
)

and my test.mdx looks like:

# Test

```js render
<button>Test</button>
```

I'm expecting to see the render attribute in the props passed to the code element but no luck.

Can you tell me if I'm missing anything?

Thanks a lot!

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.