Skip to content

Commit

Permalink
fix(sitemap): use pages to build the sitemap
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico committed May 8, 2023
1 parent 50bf66e commit c4ed905
Show file tree
Hide file tree
Showing 13 changed files with 143 additions and 20 deletions.
5 changes: 5 additions & 0 deletions .changeset/silly-impalas-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/sitemap': patch
---

Correctly emit sitemap when building website in SSG
47 changes: 29 additions & 18 deletions packages/integrations/sitemap/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
config = cfg;
},

'astro:build:done': async ({ dir, routes }) => {
'astro:build:done': async ({ dir, pages, routes }) => {
try {
if (!config.site) {
logger.warn(
Expand All @@ -84,31 +84,42 @@ const createPlugin = (options?: SitemapOptions): AstroIntegration => {
);
return;
}

let pageUrls = routes.reduce<string[]>((urls, r) => {
/**
* Dynamic URLs have entries with `undefined` pathnames
*/
if (r.pathname) {
let paths;
if (pages.length > 0) {
paths = pages.map((page) => {
/**
* remove the initial slash from relative pathname
* because `finalSiteUrl` always has trailing slash
*/
const path = finalSiteUrl.pathname + r.generate(r.pathname).substring(1);
const path = finalSiteUrl.pathname + page.pathname;

let newUrl = new URL(path, finalSiteUrl).href;
return new URL(path, finalSiteUrl).href;
});
} else {
paths = routes.reduce<string[]>((urls, route) => {
if (route.pathname) {
const path = finalSiteUrl.pathname + route.pathname.substring(1);

if (config.trailingSlash === 'never') {
urls.push(newUrl);
} else if (config.build.format === 'directory' && !newUrl.endsWith('/')) {
urls.push(newUrl + '/');
} else {
urls.push(newUrl);
urls.push(new URL(path, finalSiteUrl).href);
}
}
return urls;
}, []);
}

return urls;
}, []);
let pageUrls = paths.map((path) => {
/**
* remove the initial slash from relative pathname
* because `finalSiteUrl` always has trailing slash
*/

if (config.trailingSlash === 'never') {
return path;
} else if (config.build.format === 'directory' && !path.endsWith('/')) {
return path + '/';
} else {
return path;
}
});

try {
if (filter) {
Expand Down
23 changes: 23 additions & 0 deletions packages/integrations/sitemap/test/content.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { loadFixture, readXML } from './test-utils.js';
import { expect } from 'chai';

describe('Content collections support', () => {
/** @type {import('./test-utils.js').Fixture} */
let fixture;

before(async () => {
fixture = await loadFixture({
root: './fixtures/content/',
});
await fixture.build();
});

it('SSR pages require zero config', async () => {
const data = await readXML(fixture.readFile('/sitemap-0.xml'));
const urls = data.urlset.url;

expect(urls[0].loc[0]).to.equal('https://example.com/');
expect(urls[1].loc[0]).to.equal('https://example.com/blog/bar/');
expect(urls[2].loc[0]).to.equal('https://example.com/blog/foo/');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import sitemap from '@astrojs/sitemap';

// https://astro.build/config
export default defineConfig({
site: 'https://example.com',
integrations: [mdx(), sitemap()],
});

10 changes: 10 additions & 0 deletions packages/integrations/sitemap/test/fixtures/content/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "@test/sitemap-content",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*",
"@astrojs/sitemap": "workspace:*",
"@astrojs/mdx": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: "First post"
description: "Lorem ipsum dolor sit amet"
pubDate: "Jul 08 2022"
---
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: "Markdown Style Guide"
description: "Here is a sample of some basic Markdown syntax that can be used when writing Markdown content in Astro."
pubDate: "Jul 01 2022"
---
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { defineCollection, z } from 'astro:content';

const blog = defineCollection({
// Type-check frontmatter using a schema
schema: z.object({
title: z.string(),
description: z.string(),
// Transform string to Date object
pubDate: z
.string()
.or(z.date())
.transform((val) => new Date(val)),
updatedDate: z
.string()
.optional()
.transform((str) => (str ? new Date(str) : undefined)),
}),
});

export const collections = { blog };
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
import { CollectionEntry, getCollection } from 'astro:content';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((post) => ({
params: { slug: post.slug },
props: post,
}));
}
type Props = CollectionEntry<'blog'>;
const post = Astro.props;
const { Content } = await post.render();
---

<h1>{post.data.title}</h1>
<Content />
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import sitemap from '@astrojs/sitemap';
import nodeServer from '@astrojs/node'

export default defineConfig({
integrations: [sitemap()],
integrations: [sitemap()],
site: 'http://example.com',
output: 'server',
adapter: nodeServer({
Expand Down
3 changes: 2 additions & 1 deletion packages/integrations/sitemap/test/fixtures/ssr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"private": true,
"dependencies": {
"astro": "workspace:*",
"@astrojs/sitemap": "workspace:*"
"@astrojs/sitemap": "workspace:*",
"@astrojs/node": "workspace:*"
}
}
15 changes: 15 additions & 0 deletions pnpm-lock.yaml

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

0 comments on commit c4ed905

Please sign in to comment.