Skip to content

Commit

Permalink
Resolve mdx plugins string format (#72802)
Browse files Browse the repository at this point in the history
Implements support for passing MDX related plugins as strings instead of
as JS functions, this makes sure you can use MDX plugins with Turbopack.

This still means that e.g. the options have to be serializable, in
testing a few plugins these plugins usually have serializable options
though.

Fixes #71819
Fixes PACK-3345

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
  • Loading branch information
timneutkens authored and wyattjoh committed Nov 28, 2024
1 parent 3b36cd6 commit 5da2586
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 5 deletions.
7 changes: 4 additions & 3 deletions packages/next-mdx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,24 @@ module.exports =
(pluginOptions = {}) =>
(nextConfig = {}) => {
const extension = pluginOptions.extension || /\.mdx$/
const userProvidedMdxOptions = pluginOptions.options

const mdxRsOptions = nextConfig?.experimental?.mdxRs
const loader = mdxRsOptions
? {
loader: require.resolve('./mdx-rs-loader'),
options: {
providerImportSource: 'next-mdx-import-source-file',
...pluginOptions.options,
...userProvidedMdxOptions,
// mdxRsOptions is a union of boolean and object type of MdxTransformOptions
...(mdxRsOptions === true ? {} : mdxRsOptions),
},
}
: {
loader: require.resolve('@mdx-js/loader'),
loader: require.resolve('./mdx-js-loader'),
options: {
providerImportSource: 'next-mdx-import-source-file',
...pluginOptions.options,
...userProvidedMdxOptions,
},
}

Expand Down
66 changes: 66 additions & 0 deletions packages/next-mdx/mdx-js-loader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const mdxLoader = require('@mdx-js/loader')

function interopDefault(mod) {
return mod.default || mod
}

async function importPlugin(plugin, projectRoot) {
if (Array.isArray(plugin) && typeof plugin[0] === 'string') {
plugin[0] = interopDefault(
await import(require.resolve(plugin[0], { paths: [projectRoot] }))
)
}
return plugin
}

async function getOptions(options, projectRoot) {
const {
recmaPlugins = [],
rehypePlugins = [],
remarkPlugins = [],
...rest
} = options

const [updatedRecma, updatedRehype, updatedRemark] = await Promise.all([
Promise.all(
recmaPlugins.map((plugin) => importPlugin(plugin, projectRoot))
),
Promise.all(
rehypePlugins.map((plugin) => importPlugin(plugin, projectRoot))
),
Promise.all(
remarkPlugins.map((plugin) => importPlugin(plugin, projectRoot))
),
])

return {
...rest,
recmaPlugins: updatedRecma,
rehypePlugins: updatedRehype,
remarkPlugins: updatedRemark,
}
}

module.exports = function nextMdxLoader(...args) {
const options = this.getOptions()
const callback = this.async().bind(this)
const loaderContext = this

getOptions(options, this.context).then((userProvidedMdxOptions) => {
const proxy = new Proxy(loaderContext, {
get(target, prop, receiver) {
if (prop === 'getOptions') {
return () => userProvidedMdxOptions
}

if (prop === 'async') {
return () => callback
}

return Reflect.get(target, prop, receiver)
},
})

mdxLoader.call(proxy, ...args)
})
}
5 changes: 5 additions & 0 deletions test/e2e/app-dir/mdx/app/rehype-plugin/page.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Rehype plugin

```math
C_L
```
9 changes: 9 additions & 0 deletions test/e2e/app-dir/mdx/mdx.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ for (const type of ['with-mdx-rs', 'without-mdx-rs']) {
'@next/mdx': 'canary',
'@mdx-js/loader': '^2.2.1',
'@mdx-js/react': '^2.2.1',
'rehype-katex': '7.0.1',
},
env: {
WITH_MDX_RS: type === 'with-mdx-rs' ? 'true' : 'false',
Expand Down Expand Up @@ -59,6 +60,14 @@ for (const type of ['with-mdx-rs', 'without-mdx-rs']) {
'/_next/image?url=%2Ftest.jpg&w=384&q=75'
)
})

if (type === 'without-mdx-rs') {
it('should run plugins', async () => {
const html = await next.render('/rehype-plugin')
expect(html.includes('<mi>C</mi>')).toBe(true)
expect(html.includes('<mi>L</mi>')).toBe(true)
})
}
})

describe('pages directory', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
const withMDX = require('@next/mdx')({
import nextMDX from '@next/mdx'
const withMDX = nextMDX({
extension: /\.mdx?$/,
options: {
remarkPlugins: [],
rehypePlugins: [['rehype-katex', { strict: true, throwOnError: true }]],
},
})

/**
Expand All @@ -12,4 +17,4 @@ const nextConfig = {
},
}

module.exports = withMDX(nextConfig)
export default withMDX(nextConfig)

0 comments on commit 5da2586

Please sign in to comment.