Skip to content

Commit 13977e4

Browse files
CompuIvesjohno
authored andcommitted
Add filename info to mdx loader (#249)
1 parent 543577c commit 13977e4

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

packages/loader/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ const mdx = require('@mdx-js/mdx')
33

44
module.exports = async function(content) {
55
const callback = this.async()
6-
const options = getOptions(this)
6+
const options = Object.assign({}, getOptions(this), {filepath: this.resourcePath});
77

8-
const result = await mdx(content, options || {})
8+
const result = await mdx(content, options)
99

1010
const code = `
1111
import React from 'react'

packages/mdx/index.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,12 @@ function sync(mdx, options) {
103103
const opts = Object.assign({}, DEFAULT_OPTIONS, options)
104104
const compiler = createCompiler(opts)
105105

106-
const { contents } = compiler.processSync(mdx)
106+
const fileOpts = { contents: mdx };
107+
if (opts.filepath) {
108+
fileOpts.path = opts.filepath;
109+
}
110+
111+
const { contents } = compiler.processSync(fileOpts)
107112

108113
return contents
109114
}
@@ -112,7 +117,12 @@ async function compile(mdx, options = {}) {
112117
const opts = Object.assign({}, DEFAULT_OPTIONS, options)
113118
const compiler = createCompiler(opts)
114119

115-
const { contents } = await compiler.process(mdx)
120+
const fileOpts = { contents: mdx };
121+
if (opts.filepath) {
122+
fileOpts.path = opts.filepath;
123+
}
124+
125+
const { contents } = await compiler.process(fileOpts)
116126

117127
return contents
118128
}

packages/mdx/test/index.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,22 @@ test('Should await and render async plugins', async () => {
122122
expect(result).toMatch(/HELLO, WORLD!/)
123123
})
124124

125+
test('Should process filepath and pass it to the plugins', async () => {
126+
const result = await mdx(fixtureBlogPost, {
127+
filepath: 'hello.mdx',
128+
hastPlugins: [
129+
options => (tree, fileInfo) => {
130+
expect(fileInfo.path).toBe('hello.mdx')
131+
const headingNode = select('h1', tree)
132+
const textNode = headingNode.children[0]
133+
textNode.value = textNode.value.toUpperCase()
134+
}
135+
]
136+
})
137+
138+
expect(result).toMatch(/HELLO, WORLD!/)
139+
})
140+
125141
test(
126142
'Should parse and render footnotes',
127143
async () => {

0 commit comments

Comments
 (0)