hashicorp / next-mdx-enhanced Goto Github PK
View Code? Open in Web Editor NEWA Next.js plugin that enables MDX pages, layouts, and front matter
License: Mozilla Public License 2.0
A Next.js plugin that enables MDX pages, layouts, and front matter
License: Mozilla Public License 2.0
When I try to use any TypeScript feature (like declaring types) in my layout file, I am getting a Syntax error:
./pages/introduction.mdx:10:5
Syntax error: Unexpected token, expected ";"
8 | import navItems from '@utils/nav'
9 |
> 10 | type LayoutProps = {
| ^
11 | frontMatter: JamSauceFrontMatter
12 | }
13 |
The following config:
{
defaultLayout: true,
layoutPath: 'src/layouts',
usesSrc: true,
reExportDataFetching: true
}
Results in the following error when trying to export getStaticProps
from a layout:
Attempted import error: 'getStaticProps' is not exported from '/Users/bedwards/Projects/newhighsco/jarvenis.com/src/layouts/index' (imported as '_getStaticProps').
Changing layoutPath
to 'src/layouts` solved this issue for me, but wanted to warn anyone else who may fall into this issue
Hi there! First of all, thanks for this project! It seems like it adds some nice features to the default MDX plugin.
I'm currently trying to move to Next.js from Gatsby, and one thing that's holding me back is the excellent elboman/gatsby-remark-embedded-codesandbox.
My use case is generating sandboxes on CodeSandbox using the contents of example folders locally in my project. These are embedded using link syntax in Markdown:
<!-- before -->
[hello world example](embedded-codesandbox://hello-world-example)
<!-- after -->
<iframe src="https://codesandbox.io/api/v1/sandboxes/define?embed=1¶meters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObVSOWgLYxIgwAe7KsEAF8hAGhARyAE14EAFrTZRmNRgyaIQAHgVKAfFoBGpKQE8DAemNnLuqHuHjJMnsQTIQq-oy6q4tAAIwUlIAgF4AgB0QQzQAJ2iAbmERIA&query=hidenavigation%3D1%26view%3Dpreview" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\\" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
I'm considering how to solve this in the best way, and I wanted to ask if you would have any direction on this. I suppose taking the Gatsby Remark plugin code and creating a vanilla Remark plugin by removing the Gatsby-specific bits could work...? But maybe there are Remark plugin limitations that I'm not aware of.
If that did work like this, then I suppose I could use this with your remarkPlugins
option.
If this is too far from the topic of this package or if you cannot help, I totally understand! Just wanted to ping in case.
@jescalan Edit: in a markdown layout, you can't run
getInitialProps
or access the router since nextjs doesn't seem to recognize the layouts as page templates.
Hello again!
Loving the library and thank you again for the Windows fix. I hope I'm not being an air hog by creating another issue, but I hit another snag:
TypeError: Class constructor WithRouteWrapper cannot be invoked without 'new'
Module../layouts/FM-content.js
./layouts/FM-content.js:38
35 |
36 | // Content.getInitialProps = async props => ({...props})
37 |
> 38 | export default withRouter(ContentLayout)()
View compiled
__webpack_require__
./webpack/bootstrap:21
18 | // Execute the module function
19 | var threw = true;
20 | try {
> 21 | modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
| ^ 22 | threw = false;
23 | } finally {
24 | if(threw) delete installedModules[moduleId];
View compiled
Module../pages/about-the-law.mdx
/_next/development/server/static/development/pages/about-the-law.js:2173:111
__webpack_require__
./webpack/bootstrap:21
18 | // Execute the module function
19 | var threw = true;
20 | try {
> 21 | modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
| ^ 22 | threw = false;
23 | } finally {
24 | if(threw) delete installedModules[moduleId];
View compiled
5
/_next/development/server/static/development/pages/about-the-law.js:2330:18
__webpack_require__
./webpack/bootstrap:21
18 | // Execute the module function
19 | var threw = true;
20 | try {
> 21 | modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
| ^ 22 | threw = false;
23 | } finally {
24 | if(threw) delete installedModules[moduleId];
View compiled
I'm trying to use the withRouter
wrapper with my Layout component. Is there a better way?
next-mdx-enhanced
does not seem to play nice with next-compose-plugins
. When the two plugins are used together, next-mdx-enhanced
does not seem to have any effect:
mdx
pages return a 404 errormdx
frontmatter in other pages, Next fails to parse the file and complains about a missing loader.I've created a small app to reproduce the issue: https://github.com/connor-baer/next-mdx-enhanced-compose-plugins.
npx create-next-app
yarn add next-mdx-enhanced next-compose-plugins
next.config.js
file using the two plugins:const withPlugins = require('next-compose-plugins');
const withMdxEnhanced = require('next-mdx-enhanced');
const mdxConfig = {};
module.exports = withPlugins([[withMdxEnhanced, mdxConfig]]);
mdx
fileyarn dev
and try to load the mdx
file`npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: --------
npm ERR! Found: [email protected]
npm ERR! node_modules/next
npm ERR! next@"12.1.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer next@"9.0.x - 10.0.x" from [email protected]
npm ERR! node_modules/next-mdx-enhanced
npm ERR! next-mdx-enhanced@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /.npm/eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR! /.npm/_logs/2022-04-06T07_00_27_186Z-debug-0.log`
It seems like an issue is occurring for the newer version of the Nextjs. Its layouts feature is so impressive to work with which is not present in the next-mdx-remote version.
Hey 👋 @jescalan , I'm back with another problem that I encountered after upgrading to Next.js 9.4. I've managed to reproduce the issue here. This is really a basic setup, a create-next-app
project where I've installed next-mdx-enhanced
and babel-plugin-import-glob-array
. This causes the following error:
Attempted import error: 'frontMatter' is not exported from 'C:\dev\issue-next-mdx-enhanced-2\pages\blog\test.mdx' (imported as '_iga').
Could not find files for /blog in .next/build-manifest.json
After looking through the 9.4 changelog, I believe this is caused by the new React Refresh, although I'm not certain at all? It might be caused by the absolute path imports?
This repository also contains branch next-9.3
where I've downgraded to Next.js 9.3.6, and this works fine.
Could you please investigate this? This prevents everyone from using Next.js 9.4.
Is there a trick to getting [about](/about)
to work without reloading as we navigate? I've done it before with a "wrapper" (https://mdxjs.com/guides/wrapper-customization) but not sure that's the preferred method with this plugin.
I imagine I'm missing something in the README that's obvious to someone wiser.
Thanks for an awesome library.
All the examples show the index file in the root of the pages
directory.
I'm trying to set up a nested content library with subfolders in the docs. When I create a post index in a subdirectory, the pages.__resourcePath
property returns the relative path from the root pages
directory, and not relative to the index file location.
I'm a noob at this, and am just checking if this is the expected behaviour?
Hey,
First of all thank you for this awesome plugin, it solves a lot of things I need for MDX-Documentation at one go.
From what I can understand the extractFrontMatter function is only executed on startup / restart of the webpack dev server. This means that when I add a new mdx file in pages the frontmatter is not generated before I manually restart the dev server.
Are there any workarounds for this? How do you use the plugin in development?
I am pretty new to babel/webpack stuff, sorry if this is a noobie question. Any help would be much appreciated, thank you :)
Hey there!
Got super excited when I found this, but I'm having some issues:
Module not found: Can't resolve 'C:UsersloganProjectscensusLUCA-appealslayoutsdocs-page' in 'C:\Users\logan\Projects\census\LUCA-appeals\pages'
Might this be an OS issue? Which are you using?
When I try to deploy my site on Vercel - I get an Can't resolve .mdx-data/...json
error.
It doesn't happen locally with pnpm
(I use it) - everything builds fine in both prod
and dev
environments.
I contacted the Vercel support. Support staff tried to build the project locally with npm
and got this in output:
▲ v1rtl_site [master] NODE_ENV=production npm run build
> [email protected] build /home/paulogdm/Codes/tmp/v1rtl_site
> next build
> Using external babel configuration
> Location: "/home/paulogdm/Codes/tmp/v1rtl_site/.babelrc"
Creating an optimized production build
Failed to compile.
./.mdx-data/1069cf30b3afb243316ebb672e986d37.json
Module parse failed: Unexpected end of JSON input while parsing near ''
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
SyntaxError: Unexpected end of JSON input while parsing near ''
at JSON.parse (<anonymous>)
> Build error occurred
Error: > Build failed because of webpack errors
at build (/home/paulogdm/Codes/tmp/v1rtl_site/node_modules/next/dist/build/index.js:13:917)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/paulogdm/.npm/_logs/2020-06-04T20_46_56_918Z-debug.log
So it crashes when dependencies are installed and the project is built with npm
.
As mentioned in the issue title, it happens in Vercel deployment as well:
2020-06-03T18:41:05.449Z Failed to compile.
2020-06-03T18:41:05.449Z
2020-06-03T18:41:05.449Z ./pages/blog/index.tsx
2020-06-03T18:41:05.449Z Module not found: Can't resolve '/vercel/fe67864/.mdx-data/115651746382137e132aae2ef68bd767.json' in '/vercel/fe67864/pages/blog'
2020-06-03T18:41:05.449Z
2020-06-03T18:41:05.450Z
2020-06-03T18:41:05.450Z > Build error occurred
2020-06-03T18:41:05.451Z Error: > Build failed because of webpack errors
2020-06-03T18:41:05.451Z at build (/vercel/fe67864/node_modules/next/dist/build/index.js:13:917)
2020-06-03T18:41:05.479Z error Command failed with exit code 1.
2020-06-03T18:41:05.479Z info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
2020-06-03T18:41:05.489Z Error: Command "yarn run build" exited with 1
2020-06-03T18:41:07.101Z Done with "package.json"
The problematic page might be this one (gh source):
// pages/blog/index.tsx
import { NextPage } from 'next'
import Link from 'next/link'
import 'isomorphic-unfetch'
import { frontMatter, MDXPost } from './*.mdx'
const formatPath = (p: string) => p.replace(/\.mdx$/, '')
const PageList: NextPage = () => {
const posts = (frontMatter as MDXPost[]) || []
return (
<section>
<h1>My Blog</h1>
<div>
{posts?.map((post) => (
<Link key={post.title} href={formatPath(post.__resourcePath)}>
<a href={formatPath(post.__resourcePath)}>
<h2>{post.title}</h2>
<span>{post.date}</span>
</a>
</Link>
))}
</div>
</section>
)
}
export default PageList
I use babel-plugin-import-glob-array
, as it was recommended in readme.
More info can be found in this issue
When I install next-mdx-enhanced
and use the default config in the docs I should be able to spin up a working frontmatter enabled page.
When I run next
I get an immediate error: TypeError: Cannot read property 'indexOf' of undefined
Hi,
First of all, thank you for this great plugin that simplifies a lot the configuration process for MDX and adds pretty neat feature like layout and frontMatter... 🙂
The only drawback I see until now is performance issues with Hot Reload Module in Chrome.
When I modify layout, mdx, style or even standard js page, tab CPU is going high and freezing chrome tab for a while... Even if I am working and displaying a standard js page with no mdx content. I don't know what happens?
Do you have similar issues? Any clue on the root of this issue?
For what I have seen this is not happening in Firefox... 🤔
Thanks!
PS: If you don't have this kind of issue I could dig into my configuration in order to find a minimum project that hits this issue.
For now here is my next.config.js:
...
const withCSS = require("@zeit/next-css");
const withSass = require("@zeit/next-sass");
const withProgressBar = require("next-progressbar");
const withMdxEnhanced = require("next-mdx-enhanced")({
layoutPath: "layouts",
defaultLayout: true,
fileExtensions: ["mdx"]
});
return withProgressBar(withMdxEnhanced(withCSS(withSass(nextConfig))));
...
Hey! Love the library. I use it heavily in https://github.com/hipstersmoothie/next-ignite
Is there any way to localize the MDX files? For example I would like to add a spanish translation to my docs
Took a while to figure out what (/* your normal nextjs config */)
meant in the README. Might be good to offer a more standard complete config since the next mdx sample and standard next app scaffold don't really teach you anything.
Ended up here:
const withPlugins = require('next-compose-plugins')
const withMdxEnhanced = require('next-mdx-enhanced')
const nextConfig = {
pageExtensions: ['js', 'jsx', 'mdx', 'tsx'],
}
const mdxEnhancedConfig = {
layoutPath: 'src/layouts',
defaultLayout: true,
fileExtensions: ['mdx'],
remarkPlugins: [],
rehypePlugins: [],
extendFrontMatter: {
process: (mdxContent, frontMatter) => {},
phase: 'prebuild|loader|both',
},
}
module.exports = withPlugins([withMdxEnhanced(mdxEnhancedConfig)], nextConfig)
Hi there!
Thanks for making such a useful tool to use MDX with next.js.
I'm trying to figure out a way to pull a frontmatter variable from a parsed .mdx file into the getStaticProps function, in so that I can use that variable to load some data on build-time.
Haven't figured out an easy way to do this, due to variable scoping issues. I was wondering if there may be something I missed.
Thank you for making next-mdx-enhanced ❤️
How would you recommend using the mdxContent
that a process() receives in extendFrontMatter
? Wouldn't it be better if the content part from grey-matter was passed into extendFrontMatter instead?
Right now I'm parsing it again using grey-matter but this is already being done internally so I figured we might as well re-use that. Also, do I convert it to HTML using mdx-js and react so that I can use it in my layout?
Something like
extendFrontMatter: {
process: (mdxContent) => {
let { content } = matter(mdxContent) // this is being done by mdx-enhanced internally
/* code to render mdxContent to HTML using mdx-js and react */
return { content }
},
phase: 'prebuild',
},
Am I missing something here? My use case is fairly straightforward: an index page that shows the title as well as the first few lines from each article. Any help or ideas would be great 😅
frontmatter extraction is run over all files that match the fileExtensions
option. That means it runs over every mdx
file in every package in node_modules
. Adding md
as a supported extension then means the extraction is run over every README.md as well.
This increases compile time by itself, but also means that extending frontmatter can have a dramatic impact on compile time or stability since the expectation would normally be that only files in the pages directory would be processed.
I've been trying to get this plugin to work together with babel-plugin-import-glob-array
for a few days now, and it's been nothing but constant frustration. Everything about the plugin worked great, until I wanted to use the Babel plugin. When I try to import all my MDX files with
import { frontMatter as blogPosts } from "./blog/*.mdx";
it fails with the following error:
./pages/blog.tsx
Module not found: Can't resolve 'C:/Users/MyUser/RepoFolder/.mdx-data/51e86a315257225ee00b5e3b02f6d0f0.json' in 'C:\Users\MyUser\RepoFolder\pages'
I've checked the repository, this file does indeed not exist. When i try to import just a single MDX file with
import { frontMatter as blogPosts } from "./blog/react.mdx";
it grabs the correct cache file. It seems like the mdx-enhanced
package tries to find the *.mdx
file which doesn't exist, instead of expanding the import, which is the work of the Babel plugin
I understand that the author of this project also created the Babel plugin, so that's why I'm asking for help here. This has been really frustrating, so I hope to get it fixed as fast as possible.
I've attached a fully reproducible repository. Just clone it and run npm install
and then npm run dev
and visit /blog to see the error. I'm using TypeScript, although I think that doesn't matter.
Thanks in advance!
My repository: here
I'm trying to make a simplest layout, to get this thing working. I have the following error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
Config:
// next.config.js
const { withPlugins } = require('next-compose-plugins')
const withMdxEnhanced = require('next-mdx-enhanced')
module.exports = withPlugins(
[
withMdxEnhanced({
layoutPath: 'src/layouts/BlogLayout',
defaultLayout: true,
remarkPlugins: [],
rehypePlugins: [],
}),
],
{}
)
Layout:
// src/layouts/BlogLayout/index.tsx
import { ReactElement } from 'react'
interface Props {
children: ReactElement
}
const BlogLayout = ({ children }: Props) => {
return (
<div>
{children}
</div>
)
}
export default BlogLayout
First thanks for this awesome library, it checks all the boxes for creating documentation using Next.js and MDX.
I was wondering if there's anyway to render my pages/blog/index.mdx
as /blog
instead of /blog/index
? I don't have the slight idea of where to look to change this.
Any help appreciated!
Just would like to say thank you to everybody behind this project.
I was smashing my head trying to solve simple problems with the official lib (@next/mdx), and I couldn't believe that I would really need to parse files with fs
just to get some metadata.
It took me hours to find it, and yet it's still saving me precious time.
Thank you and keep doing a great job!
❤
Please see vercel/next.js#14325 for details.
First of all thank you for this helpful library,
I'm trying to import all blog posts with the glob pattern like this:
import { frontMatter as blogPosts } from './blog/**/*.mdx';
All my mdx files are located in src/pages/blog/...
It works fine, and I'm also recieving the contents but I have this error:
Module '"*.mdx"' has no exported member 'frontMatter'. Did you mean to use 'import frontMatter from "*.mdx"' instead?ts(2614)
Which blocks the build.
I'm using:
typescript: 3.9.3
next: 9.4.1
next-mdx-enhanced: 3.0.0
And next.config.js file:
const readingTime = require('reading-time');
const mdxPrism = require('mdx-prism');
const withMdxEnhanced = require('next-mdx-enhanced');
module.exports = withMdxEnhanced({
layoutPath: './src/layouts',
defaultLayout: true,
remarkPlugins: [
require('remark-autolink-headings'),
require('remark-slug'),
require('remark-code-titles'),
require('./src/utils/title-style')
],
rehypePlugins: [mdxPrism],
extendFrontMatter: {
process: (mdxContent) => ({
wordCount: mdxContent.split(/\s+/gu).length,
readingTime: readingTime(mdxContent)
})
}
})({
webpack: (config, { isServer }) => {
if (isServer) {
require('./scripts/generate-sitemap');
}
return config;
}
});
I wonder if it's possible to use frontMatter values inside the markdown itself, like in the example here:
https://github.com/jonschlinkert/gray-matter#optionsdelimiters
P.S. it has some custom delimeter, but the interesting part is {{title}}
https://jekyllrb.com/docs/front-matter/#custom-variables
P.S. In Jekyll it's wrapped into weird page object, but overall concept is the same
When I navigate to the MDX pages, I get this error:
pragma and pragmaFrag cannot be set when runtime is automatic.
Seeing on the latest version of react@17
and next@10
First of all, thanks for this great plugin, it solved a bunch of issues I had with next/mdx 😅️
I'm trying to use rehype-autolink-headings
and nothing seems to be happening :(
Next config
const withPlugins = require("next-compose-plugins");
const optimizedImages = require("next-optimized-images");
const withMdxEnhanced = require("next-mdx-enhanced");
const withFonts = require("next-fonts");
const nextConfig = {
pageExtensions: ["js", "jsx", "mdx", "tsx"],
};
const mdxEnhancedConfig = {
layoutPath: "src/layouts",
defaultLayout: true,
fileExtensions: ["mdx"],
remarkPlugins: [],
rehypePlugins: [
require("rehype-autolink-headings")
],
extendFrontMatter: {
process: (mdxContent, frontMatter) => {},
phase: "prebuild|loader|both",
},
};
module.exports = withPlugins(
[
[
optimizedImages,
{
optimizeImages: false,
},
],
withFonts,
withMdxEnhanced(mdxEnhancedConfig),
],
nextConfig
);
I have this heading:
## Intro
And I still get a plain old h2 without the link added.
I'm trying to install the rehype-autolink-headings
rehype plugin but nothing happens, it looks like the plugin is not being triggered.
Here is my next config:
const withMdxEnhanced = require('next-mdx-enhanced')
const withImages = require('next-images')
module.exports = withMdxEnhanced({
layoutPath: 'components/common/Layout/',
defaultLayout: false,
fileExtensions: ['mdx'],
remarkPlugins: [],
rehypePlugins: [require("rehype-autolink-headings")],
extendFrontMatter: {
process: (mdxContent, frontMatter) => {},
phase: 'prebuild|loader|both',
},
})(withImages())
Am I missing anything? Is this a bug?
Thanks,
Geraldo
Thank you so much for adding the ability to have pages under src/pages
. However, I also have my layouts under src/layout
, so I'm currently configuring the plugin like so:
{ layoutPath: './src/layouts', usesSrc: true }
Would it possible to automatically assume that layoutPath
equals src/layouts
if the project is using src/pages
?
Hey! Love the project. Trying to convert my MDX blog over to this. Hit a snag while trying to deploy. I'm seeing this error when I run next build
.
➜ next build
yarn run v1.12.3
$ next build
> Using external babel configuration
> Location: "/repo/.babelrc"
Creating an optimized production build
Failed to compile.
./pages/blog.js
Module not found: Can't resolve '/repo/.mdx-data/01bcfb81f06ba1b626478d4440916332.json' in '/repo/pages'
> Build error occurred
Error: > Build failed because of webpack errors
at build (/repo/node_modules/next/dist/build/index.js:12:900)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
If I then immediately retry the build, it works as expected. Any idea what this could be? It seems like if the .mdx-data
folder does not exist at all (which is what happens when I try to deploy) then it errors out.
I can try and get a reproducible example up if that would be helpful.
__resourcePath
is not correct on Windows. It yields values like ":\\Users\\themaxdavitt\\Documents\\example.mdx"
, which are not valid relative paths and break the "create an index page" example in the README.
It's defined here:
Lines 105 to 107 in 0ac0021
Currently, when using a folder structure where pages
is placed inside the src
folder, this plugin fails to get the correct relative path and instead uses the entire path for __resourcePath
. Since this file structure is a feature supported by Next.js, I believe support for this should be added.
Example
// When using `src` folder
import { frontMatter as blogPosts } from "./blog/*.mdx";
console.log(blogPosts.__resourcePath);
// Logs `:\\Coding\\jensmeindertsma\\src\\pages\\blog\\context.mdx`
// When `pages` is directly inside root
import { frontMatter as blogPosts } from "./blog/*.mdx";
console.log(blogPosts.__resourcePath);
// Logs `blog\context`
Is this related to babel-plugin-import-glob-array
? I'm not sure. The page itself is still accessible when using the src
folder approach, but the link to it inside src/pages/blog.tsx
is not. This is when using the exact same component found in the documentation of this plugin:
import Link from 'next/link'
import { frontMatter as docsPages} from './blog/*.mdx'
export default () => {
return (
<>
<h1>Docs Index</h1>
<ul>
{docsPages.map(page => (
<li key={page.__resourcePath}>
<Link href={formatPath(page.__resourcePath)}>
<a>{page.title}</a>
</Link>
</li>
))}
</ul>
</>
)
}
function formatPath(p) {
return p.replace(/\.mdx$/, '')
}
Currently, the content of mdx
files isn't hot reloaded, and you have to restart dev server to apply changes, - it would be more convenient to use if cache was revalidated (maybe updated_at and/or filesize check?)
Though, btw, the tool is just great anyway!
Note:- This is not exactly a bug. This library is not maintained. I have found some workarounds and created this for people who use this library and face issues like npm audit
reporting vulnerabilities, Next JS 11 Internal Server Error
. Depending on the time, this may or may not work. Use it at your own risk. It is advised to backup your project.
npm audit
ReDOS flag:-When I first used this, I found out that it had 2 severe vulnerabilities. I checked it out and found out that it had to do with the "trim
" dependency of the package remark-parse
.
The remark-parse
package uses the old version of the trim
package. Version 0.0.1 & 0.0.2 is flagged by npm audit
due to ReDOS (Regular Expression Denial of service). This issue may also happen in the next-mdx-remote
package. This flag can be ignored in most cases. If you would like to fix it, here is the workaround :-
1. Add the resolutions
property in your package.json
file. Add a object with the property of trim
and the value of a version above 0.0.2
. Here's my package.json file:-
{
"name": "samcodee-blog",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
},
"dependencies": {
"gray-matter": "^4.0.3",
"next": "^10.0.0",
"next-compose-plugins": "^2.2.1",
"next-mdx-enhanced": "^5.0.0",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "7.32.0",
"eslint-config-next": "11.1.2"
},
"resolutions": {
"trim": "^1.0.1"
}
}
2. Install Yarn
package manager. This is required for the next step. The next Step cannot be done using npm
. For this workaround, Yarn
should be used. After the workaround, you can use npm
/ Yarn
, depending on your preference.
3. Delete the node_modules
folder. Run yarn install
to install the dependencies with the new version of trim
. To maintain the lock file integrity, delete the existing package-lock.json
file and run npm i --package-lock-only
to generate the new lock file. Now, you can delete the yarn.lock
file.
Here's a script doing all of this for you:-
del package-lock.json && rmdir /S node_modules && yarn && npm i --package-lock-only && del yarn.lock
When running this, this will ask confirmation to delete the node_modules
folder. You can enter "Y
" to proceed
4. [Optional] Incase you lose the package-lock.json
file, you will have to repeat the steps again. So, you can add a script in the package.json
file. For example:-
"scripts": {
"redos":"del /S package-lock.json && rmdir /S node_modules && yarn && npm i --package-lock-only && del yarn.lock "
}
Now running npm run redos
, will do all the steps above.
5. Run npm audit
to check for vulnerabilities. It will not include the remark-parse
ReDOS vulnerability. In some cases, it might be zero. Like mine:-
6. Now, if you lose the node_modules
folder, don't worry. If you have the package-lock.json
file you generated before, you can run npm install
like every time you would do to install the dependencies. You should commit the package-lock.json
file so that others using your project can just run npm install
to install the correct dependencies instead of following the steps again. You will have to run npm run redos
if you lose the package-lock.json
file, as mentioned in Step 4.
Note:- “Regular Expression Denial of Service” means that there is a regex in the trim
package that, with malicious input, could become very slow. So an attacker can craft a special configuration string that, when passed to trim
, could slow it down exponentially. In some cases, this can be safely ignored.
Internal Server Error
on Next JS 11:-I first came across this project through this post - https://spacejelly.dev/posts/how-to-source-mdx-content-in-next-js-to-dynamically-create-pages-for-a-blog/
I thought I will create blog with this package. I created a new Next app using npx create-next-app samcodee-blog
as said in the post. It was smooth until Step 2. After following Step 2, I ran npm run dev
to start the server as mentioned in the post and navigated to http://localhost:3000
. After it loaded, I only saw a text saying Internal Server Error
:-
This happened with every route. Even http://localhost:3000/posts/hello-world . So, I thought it would be useful to check his GitHub repository and my local code for any mistakes/changes. Nothing was changed except the dependency version of Next JS. It was ^10.2.0
on his code and ^11.2.x
on my code. I installed 10.2.0
on my code and suddenly, it worked !
This happens because Next JS adopted Webpack 5 in Versions above 11. This package does not support Webpack 5. There is only one way to overcome this - downgrade to Next JS Version 10.x.x
. But, you might lose many new features in Next JS 11. I found out the you can disable Webpack 5 and use Webpack 4.
First, upgrade your next
package version to the latest by running npm install next@latest --force
( --force
because in some new versions of npm
, it will give a error. ). Next, add this line in your next.config.js - webpack5: false
. I use next-compose-plugins
package for my next.config.js
. So, here's my next config file:-
const composePlugins = require("next-compose-plugins");
const withMdxEnhanced = require("next-mdx-enhanced");
module.exports = composePlugins(
[
withMdxEnhanced({
// next-mdx-enhanced config
}),
],
{
webpack5: false
}
);
If you don't use next-compose-plugins
package, yours might look something like this:-
const withMdxEnhanced = require('next-mdx-enhanced')
module.exports = withMdxEnhanced({
// next-mdx-enhanced config
})({
webpack5: false
})
If you are a maintainer of this project and you are reading this, please add these workarounds in the README.md file so that people can use it more easily.
Anyways, thank you @hashicorp for developing such a amazing package! 😀
Any tips?
Hi friends. I regret to inform you all that this library is no longer actively maintained. We have moved on to using next-mdx-remote
, which is much faster, fits more use cases, and is more configurable.
If anyone would like to volunteer to step up and maintain this library, please respond here. Otherwise, use this at your own risk. It is specifically not compatible with webpack 5, and as soon as next.js defaults to webpack 5 as its native dependency, this library will not work with that version of next.js at all.
Hi everyone,
I want to migrate my blog from using Contentful to next-mdx-enhanced
.
Right after installing the package, creating the layout and the first mdx page I get this error
(node:7978) UnhandledPromiseRejectionWarning: TypeError: this.getOptions is not a function
at Object.loader (file:///Users/ale/Code/Local/web/myblog-conentful-nextjs/node_modules/@mdx-js/loader/lib/index.js:36:55)
at /Users/ale/Code/Local/web/myblog-conentful-nextjs/node_modules/@mdx-js/loader/index.cjs:14:19
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7978) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 7)
(node:7978) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I also have this configuration in next.config.js
module.exports = withPlugins(
[
withSourceMap,
withMdxEnhanced({
layoutPath: 'layouts',
defaultLayout: true,
fileExtensions: ['mdx', 'md'],
usesSrc: false,
reExportDataFetching: false
})
]
);
Versions:
"next": "^10.0.8",
"next-compose-plugins": "^2.2.0",
"@mdx-js/loader": "^2.1.1",
"react": "^17.0.1",
"next-mdx-enhanced": "^5.0.0"
I tried many solutions non worked for me. any ideas? Thank you
Hi,
Love this package.
Next.js' Image component got released and I am trying to use it in my blog posts written as MDX files. I am using this package.
How do I change all the 'img' tags (in the markup generated from MDX) to 'Next.js's ' tag?
Hi, can I still use this package if I am making an api call and it returns the mdx as a string?
Is there a function in the package that I can use with this string?
For reference of what I'm trying to achieve, there is a rough equivalent for Gatsby here: https://www.gatsbyjs.org/docs/mdx/programmatically-creating-pages/#make-a-template-for-your-posts
Thanks :)
Hi there! Thanks for putting this great lib together ✨
I'm moving my personal site from Gatsby to Next and trying to bring along my MDX setup.
Over there it looks something like this:
<MDXProvider components={components}>
<div className="mb-8 md:mb-10">
<h1 className="mt-8 text-3xl font-semibold leading-tight md:text-4xl lg:text-4-5xl">
{props.data.mdx.frontmatter.title}
</h1>
</div>
<MDXRenderer>{mdx.body}</MDXRenderer>
</MDXProvider>
where components
is an object mapping tags like h2
to React components, like this:
const components = {
h2: ({ children, ...rest }) => (
<h2
className="mt-12 text-lg font-semibold leading-tight text-gray-900 md:text-2xl"
{...rest}
>
{children}
</h2>
),
}
I was wondering if it this functionality was possible using next-mdx-enhanced
? I don't have webpack experience so how this is all getting wired up is a bit of a black box to me.
If not, what's the recommended way to customize the styling for MDX content?
Thank you!
The next-mdx
plugin allows for matching .md
files for compilation, but seems like its not supported here?
next-mdx-enhanced/babelPlugin.js
Lines 13 to 15 in 4413846
Will it be an easy one to add? 😊
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.