Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[MDX] Include url in glob result #3981

Merged
merged 7 commits into from
Jul 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shiny-pumpkins-return.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/mdx': patch
---

Include page url in MDX glob result
7 changes: 4 additions & 3 deletions packages/integrations/mdx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"test": "mocha --exit --timeout 20000"
},
"dependencies": {
"@mdx-js/rollup": "^2.1.1"
"@mdx-js/rollup": "^2.1.1",
"es-module-lexer": "^0.10.5"
},
"devDependencies": {
"@types/chai": "^4.3.1",
Expand All @@ -39,8 +40,8 @@
"astro": "workspace:*",
"astro-scripts": "workspace:*",
"chai": "^4.3.6",
"mocha": "^9.2.2",
"linkedom": "^0.14.12"
"linkedom": "^0.14.12",
"mocha": "^9.2.2"
},
"engines": {
"node": "^14.18.0 || >=16.12.0"
Expand Down
23 changes: 17 additions & 6 deletions packages/integrations/mdx/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import mdxPlugin from '@mdx-js/rollup';
import type { AstroIntegration } from 'astro';
import mdxPlugin from '@mdx-js/rollup';
import { parse as parseESM } from 'es-module-lexer';
import { getFileInfo } from './utils.js';

export default function mdx(): AstroIntegration {
return {
name: '@astrojs/mdx',
hooks: {
'astro:config:setup': ({ updateConfig, addPageExtension, command }: any) => {
'astro:config:setup': ({ updateConfig, config, addPageExtension, command }: any) => {
addPageExtension('.mdx');
updateConfig({
vite: {
Expand All @@ -20,14 +22,23 @@ export default function mdx(): AstroIntegration {
mdExtensions: [],
}),
},
command === 'dev' && {
{
name: '@astrojs/mdx',
transform(code: string, id: string) {
if (!id.endsWith('.mdx')) return;
// TODO: decline HMR updates until we have a stable approach
return `${code}\nif (import.meta.hot) {
const [, moduleExports] = parseESM(code);

if (!moduleExports.includes('url')) {
const { fileUrl } = getFileInfo(id, config);
code += `\nexport const url = ${JSON.stringify(fileUrl)};`;
}
if (command === 'dev') {
// TODO: decline HMR updates until we have a stable approach
code += `\nif (import.meta.hot) {
import.meta.hot.decline();
}`;
}`
}
return code;
},
},
],
Expand Down
21 changes: 21 additions & 0 deletions packages/integrations/mdx/src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { AstroConfig } from 'astro';

function appendForwardSlash(path: string) {
return path.endsWith('/') ? path : path + '/';
}

/** @see 'vite-plugin-utils' for source */
export function getFileInfo(id: string, config: AstroConfig) {
const sitePathname = appendForwardSlash(
config.site ? new URL(config.base, config.site).pathname : config.base
);

const fileId = id.split('?')[0];
let fileUrl = fileId.includes('/pages/')
? fileId.replace(/^.*?\/pages\//, sitePathname).replace(/(\/index)?\.mdx$/, '')
: undefined;
if (fileUrl && config.trailingSlash === 'always') {
fileUrl = appendForwardSlash(fileUrl);
}
return { fileId, fileUrl };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export async function get() {
const mdxPages = await import.meta.glob('./*.mdx', { eager: true });

return {
body: JSON.stringify({
urls: Object.values(mdxPages ?? {}).map(v => v?.url),
})
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# I'm a page with a url of "/test-1!"
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# I'm a page with a url of "/test-2!"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const url = '/AH!'

# I'm a test with a url override!
28 changes: 28 additions & 0 deletions packages/integrations/mdx/test/mdx-url-export.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import mdx from '@astrojs/mdx';

import { expect } from 'chai';
import { loadFixture } from '../../../astro/test/test-utils.js';

describe('MDX url export', () => {
let fixture;

before(async () => {
fixture = await loadFixture({
root: new URL('./fixtures/mdx-url-export/', import.meta.url),
integrations: [mdx()],
});

await fixture.build();
});

it('generates correct urls in glob result', async () => {
const { urls } = JSON.parse(await fixture.readFile('/pages.json'));
expect(urls).to.include('/test-1');
expect(urls).to.include('/test-2');
});

it('respects "export url" overrides in glob result', async () => {
const { urls } = JSON.parse(await fixture.readFile('/pages.json'));
expect(urls).to.include('/AH!');
});
});
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.