Dev.to post to Docusaurus blog (automation nodejs)

Pull Review with Scott Beeker - Nov 8 - - Dev Community

Hello Dev Community!
Today I'll provide you with a programmatic example of how to convert dev.to articles to a Docusaurus blog. This example will use Node.js to fetch articles from the dev.to API and create Markdown files compatible with Docusaurus blog posts.

First, let's set up the project and install the necessary dependencies:

mkdir devto-to-docusaurus
cd devto-to-docusaurus
npm init -y
npm install axios fs-extra front-matter
Enter fullscreen mode Exit fullscreen mode

Now, create a file named convert.js and add the following code:

const axios = require('axios');
const fs = require('fs-extra');
const frontMatter = require('front-matter');
const path = require('path');

const DEV_TO_API_KEY = 'YOUR_DEV_TO_API_KEY';
const DEV_TO_USERNAME = 'YOUR_DEV_TO_USERNAME';
const OUTPUT_DIR = './blog';

async function fetchDevToArticles() {
  const response = await axios.get(`https://dev.to/api/articles/me/published`, {
    headers: { 'api-key': DEV_TO_API_KEY }
  });
  return response.data;
}

function convertToDocusaurusFrontMatter(article) {
  const date = new Date(article.published_at);
  return {
    title: article.title,
    authors: [DEV_TO_USERNAME],
    tags: article.tag_list,
    date: date.toISOString().split('T')[0],
    slug: article.slug,
    description: article.description,
  };
}

async function convertArticleToMarkdown(article) {
  const frontMatterContent = convertToDocusaurusFrontMatter(article);
  const markdown = `---
${Object.entries(frontMatterContent).map(([key, value]) => `${key}: ${Array.isArray(value) ? `[${value.join(', ')}]` : value}`).join('\n')}
---

${article.body_markdown}`;

  const fileName = `${frontMatterContent.date}-${article.slug}.md`;
  const filePath = path.join(OUTPUT_DIR, fileName);
  await fs.outputFile(filePath, markdown);
  console.log(`Created: ${filePath}`);
}

async function main() {
  try {
    const articles = await fetchDevToArticles();
    await fs.ensureDir(OUTPUT_DIR);

    for (const article of articles) {
      await convertArticleToMarkdown(article);
    }

    console.log('Conversion completed successfully!');
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();
Enter fullscreen mode Exit fullscreen mode

Here's how this script works:

  1. It fetches your published articles from dev.to using the API.
  2. For each article, it converts the metadata to Docusaurus-compatible front matter.
  3. It combines the front matter with the article's Markdown content.
  4. It saves each article as a separate Markdown file in the blog directory.

To use this script:

  1. Replace YOUR_DEV_TO_API_KEY with your actual dev.to API key[1].
  2. Replace YOUR_DEV_TO_USERNAME with your dev.to username.
  3. Run the script using node convert.js.

After running the script, you'll find your dev.to articles converted to Docusaurus-compatible blog posts in the blog directory[1][3].

To integrate these posts into your Docusaurus site:

  1. Copy the generated Markdown files from the blog directory to your Docusaurus project's blog directory.
  2. Ensure your docusaurus.config.js file has the blog plugin configured correctly[1][3].

Here's an example of how your docusaurus.config.js might look:

module.exports = {
  // ... other config options
  presets: [
    [
      '@docusaurus/preset-classic',
      {
        blog: {
          path: 'blog',
          routeBasePath: 'blog',
          blogTitle: 'My Dev.to Blog',
          blogDescription: 'A collection of my dev.to articles',
          blogSidebarCount: 'ALL',
          blogSidebarTitle: 'All Blog Posts',
          showReadingTime: true,
          editUrl: 'https://github.com/yourusername/your-repo/edit/main/website/',
        },
      },
    ],
  ],
  // ... other config options
};
Enter fullscreen mode Exit fullscreen mode

This configuration sets up the blog plugin to use the blog directory and display all posts in the sidebar[1][3].

Remember to customize the editUrl and other options according to your project structure and preferences. With this setup, your dev.to articles will be seamlessly integrated into your Docusaurus blog.

Citations:
[1] https://docusaurus.io/docs/blog
[2] https://dev.to/dreamlogic/how-to-use-the-multi-blog-plugin-for-docusaurus-32a2
[3] https://docusaurus.io/docs/api/plugins/@docusaurus/plugin-content-blog
[4] https://dev.to/tuenguyen2911_67/inspired-by-docusaurus-2cm6
[5] https://dev.to/dianaiminza/documentation-using-docusaurus-40g5
[6] https://dev.to/seanyasno/starting-a-new-blogging-journey-with-docusaurus-3aap
[7] https://dev.to/lo_victoria2666/build-beautiful-documentation-websites-with-docusaurus-8o2
[8] https://dev.to/katiel/exploring-the-code-behind-docusaurus-pbk

. . .