Skip to content
MDX logo
v1.5.1GitHub logo

Webpack

MDX provides a built in webpack loader you need to install and configure for webpack projects.

Installation

npm install --save-dev @mdx-js/loader

Configuration

The loader needs to be used in tandem with the babel-loader. Most projects will typically already include this if you are using JSX syntax.

For webpack projects you can define the following webpack.config.js extension handler for .md and .mdx files:

module.exports = {
module: {
// ...
rules: [
// ...
{
test: /\.mdx?$/,
use: [
'babel-loader',
'@mdx-js/loader'
]
}
]
}
}

If you only want the loader for .mdx files you can change the regex to /\.mdx$/.

The transpiled output for MDX requires babel to be run. This is typically by adding in the babel-loader to run after the MDX loader. Webpack starts from the end of the loaders array and works backward, so it is important to follow the ordering above.

Using plugins

If you’d like to configure plugins you can do that by passing them as options:

const images = require('remark-images')
const emoji = require('remark-emoji')
module.exports = {
module: {
rules: [
{
test: /\.mdx?$/,
use: [
{
loader: 'babel-loader'
},
{
loader: '@mdx-js/loader',
options: {
remarkPlugins: [images, emoji]
}
}
]
}
]
}
}

Running MDX in the browser

If you’re running MDX in the browser you will need to configure webpack to ignore the fs module:

module.exports = {
node: {
fs: 'empty'
}
}

See the webpack docs

Babel configuration

You will also need to configure babel to support the language features that MDX uses. One way you can achieve that is using the following .babelrc at your project root.

{
"presets": [
"@babel/env",
"@babel/react"
]
}

And installing the dependencies:

npm install --save-dev @babel/preset-env @babel/preset-react
Edit this page on GitHub
Previous:
React Static
Next:
Parcel