diff --git a/.changeset/sweet-trainers-eat.md b/.changeset/sweet-trainers-eat.md new file mode 100644 index 000000000000..7a094fc48d1c --- /dev/null +++ b/.changeset/sweet-trainers-eat.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Fixes a case where `Astro.url` would be incorrect when having `build.format` set to `'preserve'` in the Astro config diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index 56faa7a7c5f1..39f848507e62 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -381,7 +381,19 @@ function getUrlForPath( * pathname: /, /foo * base: / */ - const ending = format === 'directory' ? (trailingSlash === 'never' ? '' : '/') : '.html'; + + let ending: string; + switch(format) { + case 'directory': + case 'preserve': { + ending = trailingSlash === 'never' ? '' : '/'; + break; + } + default: { + ending = '.html'; + break; + } + } let buildPathname: string; if (pathname === '/' || pathname === '') { buildPathname = base; diff --git a/packages/astro/test/fixtures/page-format/src/pages/nested/index.astro b/packages/astro/test/fixtures/page-format/src/pages/nested/index.astro index 9c077e2a381b..0f1593af6c19 100644 --- a/packages/astro/test/fixtures/page-format/src/pages/nested/index.astro +++ b/packages/astro/test/fixtures/page-format/src/pages/nested/index.astro @@ -1,8 +1,12 @@ +--- +const url = Astro.url; +--- Testing

Testing

+

{url.pathname}

diff --git a/packages/astro/test/page-format.test.js b/packages/astro/test/page-format.test.js index 7f579dae85df..d6b98b4f71e8 100644 --- a/packages/astro/test/page-format.test.js +++ b/packages/astro/test/page-format.test.js @@ -51,7 +51,35 @@ describe('build.format', () => { }); }); - describe('preserve', () => { + describe('preserve - i18n', () => { + /** @type {import('./test-utils').Fixture} */ + let fixture; + before(async () => { + fixture = await loadFixture({ + base: '/test', + root: './fixtures/page-format/', + trailingSlash: 'always', + build: { + format: 'preserve', + }, + }); + }); + + describe('Build', () => { + before(async () => { + await fixture.build(); + }); + + it('Astro.url points to right file', async () => { + let html = await fixture.readFile('/nested/index.html'); + let $ = cheerio.load(html); + console.log(html); + assert.equal($('h2').text(), '/test/nested/'); + }); + }); + }); + + describe('preserve - i18n', () => { /** @type {import('./test-utils').Fixture} */ let fixture; before(async () => { @@ -81,7 +109,7 @@ describe('build.format', () => { it('relative urls created point to sibling folders', async () => { let html = await fixture.readFile('/en/nested/page.html'); let $ = cheerio.load(html); - assert.equal($('#another').attr('href'), '/test/en/nested/another/'); + assert.equal($('#another').attr('href'), '/test/en/nested/page/another/'); }); it('index files are written as index.html', async () => {