Skip to content

Commit

Permalink
feat: localization (#4)
Browse files Browse the repository at this point in the history
* fix(locale): v1 compatibility
  • Loading branch information
ekoeryanto authored Nov 2, 2018
1 parent 8f05b88 commit df89df5
Showing 1 changed file with 58 additions and 23 deletions.
81 changes: 58 additions & 23 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const { createSitemap } = require("sitemap");
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const { createSitemap } = require('sitemap');

const log = (msg, color = "blue", label = "SITEMAP") =>
const log = (msg, color = 'blue', label = 'SITEMAP') =>
console.log(`\n${chalk.reset.inverse.bold[color](` ${label} `)} ${msg}`);

module.exports = (options, context) => {
const {
hostname,
outFile = "sitemap.xml",
changefreq = "daily",
outFile = 'sitemap.xml',
changefreq = 'daily',
cacheTime = 600,
urls = [],
...others
Expand All @@ -21,37 +21,72 @@ module.exports = (options, context) => {
if (!hostname) {
return log(
`Not generating sitemap because required 'hostname' option doesn't exist`,
"orange"
'orange'
);
}

log("Generating sitemap...");
log('Generating sitemap...');

const { pages } = context;
const _urls = pages
.map(i => {
const lastmodISO = i.lastUpdated
? new Date(i.lastUpdated).toISOString()
: undefined;
const { pages, locales } = context.getSiteData ? context.getSiteData() : context;

return {
url: i.path,
lastmodISO,
changefreq
};
})
.concat(urls);
const localeKeys = locales && Object.keys(locales);

const pagesMap = new Map();

pages.forEach(page => {
const lastmodISO = page.lastUpdated
? new Date(page.lastUpdated).toISOString()
: undefined;
pagesMap.set(page.path, { changefreq, lastmodISO });
});

if (localeKeys && localeKeys.length > 1) {
localeKeys.filter(x => x !== '/').forEach(locale => {
pagesMap.forEach((page, url) => {
if (!url.startsWith(locale)) return;

const parentURL = url.replace(locale, '/');
const parentPage = pagesMap.get(parentURL);
if (parentPage) {
if (!parentPage.links) {
parentPage.links = [
{
lang: locales['/'].lang,
url: parentURL
}
];
}

parentPage.links.push({
lang: locales[locale].lang,
url
});
}

pagesMap.set(parentURL, parentPage);
pagesMap.delete(url);
});
});
}

const sitemap = createSitemap({
hostname: hostname,
cacheTime: cacheTime * 1000,
urls: _urls,
...others
});

pagesMap.forEach((page, url) => {
sitemap.add({ url, ...page });
});

// add custom urls
urls.forEach(url => sitemap.add(url));

log(`found ${sitemap.urls.length} locations`);
const sitemapXML = path.resolve(context.outDir || options.dest, outFile);

fs.writeFileSync(sitemapXML, sitemap.toString());
log(`${sitemap.urls.length} locations have been written.`);
}
};
};

0 comments on commit df89df5

Please sign in to comment.