diff --git a/.changeset/hungry-pens-develop.md b/.changeset/hungry-pens-develop.md new file mode 100644 index 000000000000..c5e7876c7f20 --- /dev/null +++ b/.changeset/hungry-pens-develop.md @@ -0,0 +1,5 @@ +--- +'@astrojs/mdx': patch +--- + +Fix MDX style imports when layout is not applied diff --git a/packages/integrations/mdx/src/index.ts b/packages/integrations/mdx/src/index.ts index 72fbbeb6ca8d..6516e4b12193 100644 --- a/packages/integrations/mdx/src/index.ts +++ b/packages/integrations/mdx/src/index.ts @@ -119,6 +119,11 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration { // These transforms must happen *after* JSX runtime transformations transform(code, id) { if (!id.endsWith('.mdx')) return; + + // Ensures styles and scripts are injected into a `` + // When a layout is not applied + code += `\nMDXContent[Symbol.for('astro.needsHeadRendering')] = !Boolean(frontmatter.layout);`; + const [, moduleExports] = parseESM(code); const { fileUrl, fileId } = getFileInfo(id, config); diff --git a/packages/integrations/mdx/test/fixtures/mdx-page/src/pages/index.mdx b/packages/integrations/mdx/test/fixtures/mdx-page/src/pages/index.mdx index 195881e02f18..2c9af4d03a43 100644 --- a/packages/integrations/mdx/test/fixtures/mdx-page/src/pages/index.mdx +++ b/packages/integrations/mdx/test/fixtures/mdx-page/src/pages/index.mdx @@ -1 +1,3 @@ +import '../styles.css' + # Hello page! diff --git a/packages/integrations/mdx/test/fixtures/mdx-page/src/styles.css b/packages/integrations/mdx/test/fixtures/mdx-page/src/styles.css new file mode 100644 index 000000000000..7d5c79e1e647 --- /dev/null +++ b/packages/integrations/mdx/test/fixtures/mdx-page/src/styles.css @@ -0,0 +1,3 @@ +p { + color: red; +} diff --git a/packages/integrations/mdx/test/mdx-page.test.js b/packages/integrations/mdx/test/mdx-page.test.js index d0b0a80782de..4c3605651c42 100644 --- a/packages/integrations/mdx/test/mdx-page.test.js +++ b/packages/integrations/mdx/test/mdx-page.test.js @@ -26,6 +26,15 @@ describe('MDX Page', () => { expect(h1.textContent).to.equal('Hello page!'); }); + + it('injects style imports when layout is not applied', async () => { + const html = await fixture.readFile('/index.html'); + const { document } = parseHTML(html); + + const stylesheet = document.querySelector('link[rel="stylesheet"]'); + + expect(stylesheet).to.not.be.null; + }) }); describe('dev', () => {