Site icon Blog ARC Optimizer

Construire un blog avec Angular en moins de 30 minutes en utilisant Analog


Apprenez à créer un blog en utilisant Angular et Analog. Ce didacticiel vous guidera tout au long du processus de mise en place d’un blog alimenté par Markdown utilisant Analog.

Vous avez toujours voulu construire un blog avec Angular, mais vous souhaitez que ce soit aussi simple que d’écrire Markdown et de faire de la publication? Je vais vous montrer comment faire cela en moins de 30 minutes. Ce tutoriel vous guidera à travers la construction d’un blog alimenté par Markdown en utilisant Analogique—Un méta-trame pour Angular qui apporte la génération de sites statiques, le routage de contenu et tous les goodies modernes que vous aimerez.

Nous allons couvrir les sujets suivants:

  • Créer des articles de blog avec Markdown
  • Affichage des messages et des itinéraires de construction
  • Prérenfication de la page statique (hybride-SSR)
  • Générer un plan du site

Commençons!

Configuration du projet

Nous allons commencer par créer un nouveau projet analogique. Vous aurez besoin de Node.js et NPM (ou PNPM / YARN) installés.

Ouvrez le terminal et exécutez la commande npx create-analog@latest my-analog-blog Pour créer le projet. Vous obtiendrez une invite pour choisir la façon dont vous souhaitez que le projet soit échafaudé. Choisissez le « Blog » Option car c’est ce que nous voulons construire.

Il vous sera demandé de choisir un surligneur de syntaxe pour le blog. Allons avec shiki pour ce tutoriel.

L’invite suivante vous demandera si vous souhaitez utiliser des composants de fichier unique (SFC). Sélectionner Non (N) pour utiliser la structure des composants angulaires traditionnels.

L’invite suivante vous demandera si vous souhaitez utiliser CSS à vent arrière. C’est facultatif, mais c’est un excellent choix pour styliser rapidement votre blog. Si vous choisissez Oui (Y), Analog le configurera pour vous.

Après tout cela, le projet doit être créé avec un référentiel GIT initialisé. Exécutez les commandes suivantes pour installer les dépendances et commencer à développer votre blog:

Vous pouvez avoir la CLI ajouter "marked": "^7.0.0" à votre package.json dossier, mais @analog/content A une version supérieure spécifiée comme dépendance des pairs. Changer la version de marked à ^15.0.0 dans votre package.json Avant de courir npm install.

cd my-analog-blog
npm install

Le projet est désormais prêt pour nous à ajouter / publier du contenu et à le coiffer à notre goût. Nous allons parcourir le code qui fait que cela fonctionne dans les sections suivantes, mais ajoutons d’abord un post et voyons à quoi cela ressemble.

Ajouter un fichier Markdown nommé hello-world.md au src/content/blog/ dossier. Collez ensuite dans le contenu suivant:

---
title: "Hello World: Using Analog & Angular"
slug: "hello-world"
description: "My first Analog blog post!"
coverImage: "https://images.unsplash.com/photo-1493612276216-ee3925520721?auto=format&fit=crop&w=464&q=80"
---

Here is a sample of some basic Markdown syntax that can be used when writing Markdown content in Astro.

## Headings

The following HTML `<h1>``<h6>` elements represent six levels of section headings. `<h1>` is the highest section level while `<h6>` is the lowest.

# H1

## H2

### H3

#### H4

##### H5

###### H6

## Paragraph

Xerum, quo qui aut unt expliquam qui dolut labo. Aque venitatiusda cum, voluptionse latur sitiae dolessi aut parist aut dollo enim qui voluptate ma dolestendit peritin re plis aut quas inctum laceat est volestemque commosa as cus endigna tectur, offic to cor sequas etum rerum idem sintibus eiur? Quianimin porecus evelectur, cum que nis nust voloribus ratem aut omnimi, sitatur? Quiatem. Nam, omnis sum am facea corem alique molestrunt et eos evelece arcillit ut aut eos eos nus, sin conecerem erum fuga. Ri oditatquam, ad quibus unda veliamenimin cusam et facea ipsamus es exerum sitate dolores editium rerore eost, temped molorro ratiae volorro te reribus dolorer sperchicium faceata tiustia prat.

Itatur? Quiatae cullecum rem ent aut odis in re eossequodi nonsequ idebis ne sapicia is sinveli squiatum, core et que aut hariosam ex eat.

## Blockquotes

The blockquote element represents content that is quoted from another source, optionally with a citation which must be within a `footer` or `cite` element, and optionally with in-line changes such as annotations and abbreviations.

Voyons comment le blog est rendu.

Ouvrez le terminal et exécutez le npm run dev commande. Cela commence votre application angulaire. Ouvrir http: // localhost: 5173 / Et vous devriez voir les blogs répertoriés.

Travailler avec le contenu de Markdown

Cela ressemble à de la magie, mais vous avez maintenant un blog de Markdown fonctionnel. Le projet échafaudé avait déjà les fichiers et dépendances nécessaires. Mais comment ça marche? Décomposons-le.

Rendu des routes de démarque et de contenu

Analog utilise le @analogjs/content Package pour gérer le contenu Markdown. Il fournit une API puissante pour le chargement et le rendu des fichiers de démarrage. Nous avons utilisé le provideContent() fonction, avec le withMarkdownRenderer() et withShikiHighlighter() dans le src/app/app.config.ts déposer. Le withMarkdownRenderer() La fonction est responsable du rendu du contenu Markdown, tandis que le withShikiHighlighter() La fonction est responsable de la mise en évidence des blocs de code à l’aide de Shiki. Outre Shiki, il a un support intégré pour PrismJS, qui peut être activé en utilisant le withPrismHighlighter() fonction transmise à provideContent().

Tout cela permet de rendre le contenu de Markdown dans le src/content dossier comme vous l’avez vu plus tôt. Il permet également d’avoir une page de démarrage dans le src/app/pages dossier. Par exemple, si vous créez un fichier appelé src/app/pages/about.mdil sera rendu comme page à /about. Essayons cela.

Ajouter un fichier appelé about.md dans le src/app/pages dossier avec le contenu suivant:

---
title: About Me
meta:
  - name: description
    content: This is the about me page
  - property: og:title
    content: About Page
---

## About Analog

I'm a software engineer with a passion for building web applications. I love using Angular and Analog to create fast, modern websites.

[Back Home](/)

Le meta Le champ est facultatif. Il vous permet d’ajouter des balises de méta à des fins de référencement. Le title Le champ est utilisé comme titre de page.

Sauvez cela et visitez /about dans le navigateur pour voir votre nouvelle page.

Collection de contenu Markdown

Analog vous donne un moyen flexible de collecter et de stocker des fichiers de démarque dans votre projet. Au lieu d’avoir des fichiers de marque individuels dans le pages répertoire, vous pouvez les mettre dans le src/content annuaire. Ceci est utile pour les blogs, la documentation ou tout autre contenu qui doit être organisé. Ces fichiers de marque prennent en charge avantage pour les métadonnées. Vous l’avez déjà vu lorsque vous avez ajouté des fichiers Markdown dans la section précédente.

Page de liste de blogs

Le pages/blog/index.page.ts Le fichier est responsable du rendu de la liste des articles de blog. Il utilise le injectContentFiles() Fonction pour récupérer la liste des fichiers Markdown dans le src/content/ annuaire. Nous obtenons les listes et l’injectons dans le composant de page comme suit:

export default class BlogComponent {
  readonly posts = injectContentFiles<PostAttributes>();
}

Le PostAttributes L’interface définit la structure de la matière frontale pour chaque post, et vous pouvez ajouter plus de champs au besoin.

Le modèle du composant rend ensuite une liste de publications à l’aide de ces données:

<h1>Blog Archive</h1>

@for (post of posts; track post.attributes.slug) {
<a [routerLink]="['/blog/', post.attributes.slug]">
  <h2 class="post__title">{{ post.attributes.title }}</h2>
  <p class="post__desc">{{ post.attributes.description }}</p>
</a>
}

Ce code utilise le @for Directive pour parcourir chaque post et afficher son titre et sa description. Le routerLink La directive crée un lien vers la page de billet de blog individuel, où slug est utilisé comme limace URL du poteau.

Page de blog

L’analogue fournit un MarkdownComponent et injectContent() Fonction pour rendre le contenu Markdown avec Front Matter.

Le pages/blog/[slug].page.ts Le fichier est responsable du rendu du billet de blog individuel. Il utilise le injectContent() Fonction pour récupérer le contenu du fichier Markdown en fonction de la limace dans l’URL. Le modèle du composant utilise le MarkdownComponent Pour rendre le contenu comme vous pouvez le voir ci-dessous:

@Component({
  selector: "app-blog-post",
  standalone: true,
  imports: [AsyncPipe, MarkdownComponent],
  template: `
    @if (post$ | async; as post) {
      <article>
        <img class="post__image" [src]="post.attributes.coverImage" />
        <analog-markdown 

Learn how to build a blog using Angular and Analog. This tutorial will guide you through the process of setting up a Markdown-powered blog using Analog.

Ever wanted to build a blog with Angular, but wished it was as easy as writing Markdown and hitting publish? I’ll show you how to do that in under 30 minutes. This tutorial will walk you through building a Markdown-powered blog using Analog—a meta-framework for Angular that brings static site generation, content routing and all the modern goodies you’ll love.

We’re going to cover the following topics:

  • Creating blog posts with Markdown
  • Displaying posts and building routes
  • Static page prerendering (Hybrid-SSR)
  • Generating a sitemap

Let’s get started!

Project Setup

We’ll start with creating a new Analog project. You’ll need Node.js and npm (or pnpm/yarn) installed.

Open the terminal and run the command npx create-analog@latest my-analog-blog to create the project. You’ll get a prompt to choose how you’d like the project to be scaffolded. Choose the “Blog” option since that’s what we want to build.

You’ll be asked to choose a syntax highlighter for the blog. Let’s go with shiki for this tutorial.

The next prompt will ask if you want to use single file components (SFC). Select no (N) to use the traditional Angular component structure.

The next prompt will ask if you want to use Tailwind CSS. This is optional, but it’s a great choice for styling your blog quickly. If you choose yes (Y), Analog will set it up for you.

After all that, the project should be created with a Git repository initialized. Run the following commands to install the dependencies and start developing your blog:

You may have the CLI add "marked": "^7.0.0" to your package.json file, but @analog/content has a higher version specified as its peer dependency. Change the version of marked to ^15.0.0 in your package.json before you run npm install.

cd my-analog-blog
npm install

The project is now ready for us to add/publish content and style it to our liking. We will walk through the code that makes this work in the following sections, but first let’s add a post and see how it looks.

Add a Markdown file named hello-world.md to the src/content/blog/ folder. Then paste in the following content:

---
title: "Hello World: Using Analog & Angular"
slug: "hello-world"
description: "My first Analog blog post!"
coverImage: "https://images.unsplash.com/photo-1493612276216-ee3925520721?auto=format&fit=crop&w=464&q=80"
---

Here is a sample of some basic Markdown syntax that can be used when writing Markdown content in Astro.

## Headings

The following HTML `<h1>``<h6>` elements represent six levels of section headings. `<h1>` is the highest section level while `<h6>` is the lowest.

# H1

## H2

### H3

#### H4

##### H5

###### H6

## Paragraph

Xerum, quo qui aut unt expliquam qui dolut labo. Aque venitatiusda cum, voluptionse latur sitiae dolessi aut parist aut dollo enim qui voluptate ma dolestendit peritin re plis aut quas inctum laceat est volestemque commosa as cus endigna tectur, offic to cor sequas etum rerum idem sintibus eiur? Quianimin porecus evelectur, cum que nis nust voloribus ratem aut omnimi, sitatur? Quiatem. Nam, omnis sum am facea corem alique molestrunt et eos evelece arcillit ut aut eos eos nus, sin conecerem erum fuga. Ri oditatquam, ad quibus unda veliamenimin cusam et facea ipsamus es exerum sitate dolores editium rerore eost, temped molorro ratiae volorro te reribus dolorer sperchicium faceata tiustia prat.

Itatur? Quiatae cullecum rem ent aut odis in re eossequodi nonsequ idebis ne sapicia is sinveli squiatum, core et que aut hariosam ex eat.

## Blockquotes

The blockquote element represents content that is quoted from another source, optionally with a citation which must be within a `footer` or `cite` element, and optionally with in-line changes such as annotations and abbreviations.

Let’s see how the blog is rendered.

Open the terminal and run the npm run dev command. This starts your Angular app. Open http://localhost:5173/ and you should see the blogs listed.

Working with Markdown Content

It feels like magic, but you now have a functional Markdown blog. The scaffolded project already had the necessary files and dependencies. But how does it work? Let’s break it down.

Rendering Markdown and Content Routes

Analog uses the @analogjs/content package to handle Markdown content. It provides a powerful API for loading and rendering Markdown files. We used the provideContent() function, along with the withMarkdownRenderer() and withShikiHighlighter() in the src/app/app.config.ts file. The withMarkdownRenderer() function is responsible for rendering the Markdown content, while the withShikiHighlighter() function is responsible for highlighting the code blocks using Shiki. Besides Shiki, it has built-in support for PrismJS, which can be enabled using the withPrismHighlighter() function passed to provideContent().

All these make it possible to render the Markdown content in the src/content folder as you saw earlier. It also makes it possible to have a Markdown page in the src/app/pages folder. For example, if you create a file called src/app/pages/about.md, it will be rendered as a page at /about. Let’s try that.

Add a file called about.md in the src/app/pages folder with the following content:

---
title: About Me
meta:
  - name: description
    content: This is the about me page
  - property: og:title
    content: About Page
---

## About Analog

I'm a software engineer with a passion for building web applications. I love using Angular and Analog to create fast, modern websites.

[Back Home](/)

The meta field is optional. It allows you to add meta tags for SEO purposes. The title field is used as the page title.

Save that and visit /about in the browser to see your new page.

Markdown Content Collection

Analog gives you a flexible way to collect and store markdown files in your project. Instead of having individual markdown files in the pages directory, you can put them in the src/content directory. This is useful for blogs, documentation or any other content that needs to be organized. These Markdown files support front matter for metadata. You’ve seen this already when you added Markdown files in the previous section.

Blog List Page

The pages/blog/index.page.ts file is responsible for rendering the list of blog posts. It uses the injectContentFiles() function to fetch the list of Markdown files in the src/content/ directory. We get the lists and inject it into the Page component as follows:

export default class BlogComponent {
  readonly posts = injectContentFiles<PostAttributes>();
}

The PostAttributes interface defines the structure of the front matter for each post, and you can add more fields as needed.

The component’s template then renders a list of posts using that data:

<h1>Blog Archive</h1>

@for (post of posts; track post.attributes.slug) {
<a [routerLink]="['/blog/', post.attributes.slug]">
  <h2 class="post__title">{{ post.attributes.title }}</h2>
  <p class="post__desc">{{ post.attributes.description }}</p>
</a>
}

This code uses the @for directive to loop through each post and display its title and description. The routerLink directive creates a link to the individual blog post page, where slug is used as the post’s URL slug.

Blog Post Page

Analog provides a MarkdownComponent and injectContent() function for rendering Markdown content with front matter.

The pages/blog/[slug].page.ts file is responsible for rendering the individual blog post. It uses the injectContent() function to fetch the content of the Markdown file based on the slug in the URL. The component’s template uses the MarkdownComponent to render the content as you can see below:

@Component({
  selector: "app-blog-post",
  standalone: true,
  imports: [AsyncPipe, MarkdownComponent],
  template: `
    @if (post$ | async; as post) {
      <article>
        <img class="post__image" [src]="post.attributes.coverImage" />
        <analog-markdown [content]="post.content" />
      </article>
    }
  `,
  styles: `
    .post__image {
      max-height: 40vh;
    }
  `,
})
export default class BlogPostComponent {
  readonly post$ = injectContent<PostAttributes>("slug");
}

You may have noticed that rendering Markdown with the MarkdownComponent is as simple as <analog-markdown [content]="post.content" />. It applies the necessary HTML and uses Shiki to highlight code blocks.

You still have the flexibility to customize the CSS styles for the rendered Markdown content.

Prerendering Static Pages

Analog supports server-side rendering, static site generation (SSG) and a hybrid approach. By hybrid, I mean a mix of server-rendered dynamic pages and prerendered static pages. By default, Analog apps are configured as SSR, but we’re going to configure the blog routes to be prerendered static pages. This is awesome for performance and SEO, while still allowing you to have dynamic pages for other parts of your site.

When you open vite.config.ts, you’ll see the Analog plugin config:

export default defineConfig(({ mode }) => ({
  // collapsed code block
  plugins: [
    analog({
      content: {
        highlighter: "shiki",
      },
      prerender: {
        routes: ["/blog", "/blog/2022-12-27-my-first-post"],
      },
    }),
  ],
  // collapsed code block
}));

The /blog and /blog/2022-12-27-my-first-post routes are prerendered. What we want is to prerender all the blog posts from the content directory. We’re going to need an object that loads the list of content and return the urls to pre-render.

Let’s add an object to the routes config to prerender the contents from the content directory. Update the routes config to the following:

prerender: {
  routes: async () => [
    "/blog",
    {
      contentDir: "src/content/blog",
      transform: (file: PrerenderContentFile) => {
        // use the slug from frontmatter if defined, otherwise use the file's basename
        const slug = file.attributes["slug"] || file.name;
        return `/blog/${slug}`;
      },
    },
  ],
},

The transform function maps the file paths to the URLs. The returned string should be the URL path in your app. The contentDir value is the path to the content directory, but it can also be a glob pattern.

Autogenerate a Sitemap

Sitemaps help search engines discover your content. Analog can generate a sitemap automatically when you enable the sitemap option in the prerender config. To make your blog discoverable by search engines, enable the sitemap option:

prerender: {
  // the existing routes config
  sitemap: {
    host: 'https://pmbanugo.me/',
  },
},

After building the site, you’ll find the sitemap in the dist/analog/public directory.

That’s a Wrap!

You now have a Markdown-powered blog built with Angular and complete with a sitemap. While we used the default styling from the template, you can customize it using your favorite UI library. You can also enhance your blog by setting up an API route to dynamically generate open graph images for each blog post.

You can copy or clone the source code from this tutorial to get started with your own blog.

Happy blogging!

="post.content" />
</article>
}
`

,
styles: `
.post__image {
max-height: 40vh;
}
`
,
})
export default class BlogPostComponent {
readonly post$ = injectContent<PostAttributes>("slug");
}

Vous avez peut-être remarqué que le rendu de la marque avec le MarkdownComponent est aussi simple que <analog-markdown

Learn how to build a blog using Angular and Analog. This tutorial will guide you through the process of setting up a Markdown-powered blog using Analog.

Ever wanted to build a blog with Angular, but wished it was as easy as writing Markdown and hitting publish? I’ll show you how to do that in under 30 minutes. This tutorial will walk you through building a Markdown-powered blog using Analog—a meta-framework for Angular that brings static site generation, content routing and all the modern goodies you’ll love.

We’re going to cover the following topics:

  • Creating blog posts with Markdown
  • Displaying posts and building routes
  • Static page prerendering (Hybrid-SSR)
  • Generating a sitemap

Let’s get started!

Project Setup

We’ll start with creating a new Analog project. You’ll need Node.js and npm (or pnpm/yarn) installed.

Open the terminal and run the command npx create-analog@latest my-analog-blog to create the project. You’ll get a prompt to choose how you’d like the project to be scaffolded. Choose the “Blog” option since that’s what we want to build.

You’ll be asked to choose a syntax highlighter for the blog. Let’s go with shiki for this tutorial.

The next prompt will ask if you want to use single file components (SFC). Select no (N) to use the traditional Angular component structure.

The next prompt will ask if you want to use Tailwind CSS. This is optional, but it’s a great choice for styling your blog quickly. If you choose yes (Y), Analog will set it up for you.

After all that, the project should be created with a Git repository initialized. Run the following commands to install the dependencies and start developing your blog:

You may have the CLI add "marked": "^7.0.0" to your package.json file, but @analog/content has a higher version specified as its peer dependency. Change the version of marked to ^15.0.0 in your package.json before you run npm install.

cd my-analog-blog
npm install

The project is now ready for us to add/publish content and style it to our liking. We will walk through the code that makes this work in the following sections, but first let’s add a post and see how it looks.

Add a Markdown file named hello-world.md to the src/content/blog/ folder. Then paste in the following content:

---
title: "Hello World: Using Analog & Angular"
slug: "hello-world"
description: "My first Analog blog post!"
coverImage: "https://images.unsplash.com/photo-1493612276216-ee3925520721?auto=format&fit=crop&w=464&q=80"
---

Here is a sample of some basic Markdown syntax that can be used when writing Markdown content in Astro.

## Headings

The following HTML `<h1>``<h6>` elements represent six levels of section headings. `<h1>` is the highest section level while `<h6>` is the lowest.

# H1

## H2

### H3

#### H4

##### H5

###### H6

## Paragraph

Xerum, quo qui aut unt expliquam qui dolut labo. Aque venitatiusda cum, voluptionse latur sitiae dolessi aut parist aut dollo enim qui voluptate ma dolestendit peritin re plis aut quas inctum laceat est volestemque commosa as cus endigna tectur, offic to cor sequas etum rerum idem sintibus eiur? Quianimin porecus evelectur, cum que nis nust voloribus ratem aut omnimi, sitatur? Quiatem. Nam, omnis sum am facea corem alique molestrunt et eos evelece arcillit ut aut eos eos nus, sin conecerem erum fuga. Ri oditatquam, ad quibus unda veliamenimin cusam et facea ipsamus es exerum sitate dolores editium rerore eost, temped molorro ratiae volorro te reribus dolorer sperchicium faceata tiustia prat.

Itatur? Quiatae cullecum rem ent aut odis in re eossequodi nonsequ idebis ne sapicia is sinveli squiatum, core et que aut hariosam ex eat.

## Blockquotes

The blockquote element represents content that is quoted from another source, optionally with a citation which must be within a `footer` or `cite` element, and optionally with in-line changes such as annotations and abbreviations.

Let’s see how the blog is rendered.

Open the terminal and run the npm run dev command. This starts your Angular app. Open http://localhost:5173/ and you should see the blogs listed.

Working with Markdown Content

It feels like magic, but you now have a functional Markdown blog. The scaffolded project already had the necessary files and dependencies. But how does it work? Let’s break it down.

Rendering Markdown and Content Routes

Analog uses the @analogjs/content package to handle Markdown content. It provides a powerful API for loading and rendering Markdown files. We used the provideContent() function, along with the withMarkdownRenderer() and withShikiHighlighter() in the src/app/app.config.ts file. The withMarkdownRenderer() function is responsible for rendering the Markdown content, while the withShikiHighlighter() function is responsible for highlighting the code blocks using Shiki. Besides Shiki, it has built-in support for PrismJS, which can be enabled using the withPrismHighlighter() function passed to provideContent().

All these make it possible to render the Markdown content in the src/content folder as you saw earlier. It also makes it possible to have a Markdown page in the src/app/pages folder. For example, if you create a file called src/app/pages/about.md, it will be rendered as a page at /about. Let’s try that.

Add a file called about.md in the src/app/pages folder with the following content:

---
title: About Me
meta:
  - name: description
    content: This is the about me page
  - property: og:title
    content: About Page
---

## About Analog

I'm a software engineer with a passion for building web applications. I love using Angular and Analog to create fast, modern websites.

[Back Home](/)

The meta field is optional. It allows you to add meta tags for SEO purposes. The title field is used as the page title.

Save that and visit /about in the browser to see your new page.

Markdown Content Collection

Analog gives you a flexible way to collect and store markdown files in your project. Instead of having individual markdown files in the pages directory, you can put them in the src/content directory. This is useful for blogs, documentation or any other content that needs to be organized. These Markdown files support front matter for metadata. You’ve seen this already when you added Markdown files in the previous section.

Blog List Page

The pages/blog/index.page.ts file is responsible for rendering the list of blog posts. It uses the injectContentFiles() function to fetch the list of Markdown files in the src/content/ directory. We get the lists and inject it into the Page component as follows:

export default class BlogComponent {
  readonly posts = injectContentFiles<PostAttributes>();
}

The PostAttributes interface defines the structure of the front matter for each post, and you can add more fields as needed.

The component’s template then renders a list of posts using that data:

<h1>Blog Archive</h1>

@for (post of posts; track post.attributes.slug) {
<a [routerLink]="['/blog/', post.attributes.slug]">
  <h2 class="post__title">{{ post.attributes.title }}</h2>
  <p class="post__desc">{{ post.attributes.description }}</p>
</a>
}

This code uses the @for directive to loop through each post and display its title and description. The routerLink directive creates a link to the individual blog post page, where slug is used as the post’s URL slug.

Blog Post Page

Analog provides a MarkdownComponent and injectContent() function for rendering Markdown content with front matter.

The pages/blog/[slug].page.ts file is responsible for rendering the individual blog post. It uses the injectContent() function to fetch the content of the Markdown file based on the slug in the URL. The component’s template uses the MarkdownComponent to render the content as you can see below:

@Component({
  selector: "app-blog-post",
  standalone: true,
  imports: [AsyncPipe, MarkdownComponent],
  template: `
    @if (post$ | async; as post) {
      <article>
        <img class="post__image" [src]="post.attributes.coverImage" />
        <analog-markdown [content]="post.content" />
      </article>
    }
  `,
  styles: `
    .post__image {
      max-height: 40vh;
    }
  `,
})
export default class BlogPostComponent {
  readonly post$ = injectContent<PostAttributes>("slug");
}

You may have noticed that rendering Markdown with the MarkdownComponent is as simple as <analog-markdown [content]="post.content" />. It applies the necessary HTML and uses Shiki to highlight code blocks.

You still have the flexibility to customize the CSS styles for the rendered Markdown content.

Prerendering Static Pages

Analog supports server-side rendering, static site generation (SSG) and a hybrid approach. By hybrid, I mean a mix of server-rendered dynamic pages and prerendered static pages. By default, Analog apps are configured as SSR, but we’re going to configure the blog routes to be prerendered static pages. This is awesome for performance and SEO, while still allowing you to have dynamic pages for other parts of your site.

When you open vite.config.ts, you’ll see the Analog plugin config:

export default defineConfig(({ mode }) => ({
  // collapsed code block
  plugins: [
    analog({
      content: {
        highlighter: "shiki",
      },
      prerender: {
        routes: ["/blog", "/blog/2022-12-27-my-first-post"],
      },
    }),
  ],
  // collapsed code block
}));

The /blog and /blog/2022-12-27-my-first-post routes are prerendered. What we want is to prerender all the blog posts from the content directory. We’re going to need an object that loads the list of content and return the urls to pre-render.

Let’s add an object to the routes config to prerender the contents from the content directory. Update the routes config to the following:

prerender: {
  routes: async () => [
    "/blog",
    {
      contentDir: "src/content/blog",
      transform: (file: PrerenderContentFile) => {
        // use the slug from frontmatter if defined, otherwise use the file's basename
        const slug = file.attributes["slug"] || file.name;
        return `/blog/${slug}`;
      },
    },
  ],
},

The transform function maps the file paths to the URLs. The returned string should be the URL path in your app. The contentDir value is the path to the content directory, but it can also be a glob pattern.

Autogenerate a Sitemap

Sitemaps help search engines discover your content. Analog can generate a sitemap automatically when you enable the sitemap option in the prerender config. To make your blog discoverable by search engines, enable the sitemap option:

prerender: {
  // the existing routes config
  sitemap: {
    host: 'https://pmbanugo.me/',
  },
},

After building the site, you’ll find the sitemap in the dist/analog/public directory.

That’s a Wrap!

You now have a Markdown-powered blog built with Angular and complete with a sitemap. While we used the default styling from the template, you can customize it using your favorite UI library. You can also enhance your blog by setting up an API route to dynamically generate open graph images for each blog post.

You can copy or clone the source code from this tutorial to get started with your own blog.

Happy blogging!

="post.content" />. Il applique le HTML nécessaire et utilise Shiki pour mettre en surbrillance les blocs de code.

Vous avez toujours la flexibilité de personnaliser les styles CSS pour le contenu Markdown rendu.

Prérencier les pages statiques

Analog prend en charge le rendu côté serveur, la génération de sites statiques (SSG) et une approche hybride. Par hybride, je veux dire un mélange de pages dynamiques rendues par le serveur et de pages statiques prépendantes. Par défaut, les applications analogiques sont configurées comme SSR, mais nous allons configurer les itinéraires de blog pour être préenduré des pages statiques. C’est génial pour les performances et le référencement, tout en vous permettant d’avoir des pages dynamiques pour d’autres parties de votre site.

Lorsque vous ouvrez vite.config.tsvous verrez la configuration du plugin analogique:

export default defineConfig(({ mode }) => ({
  
  plugins: [
    analog({
      content: {
        highlighter: "shiki",
      },
      prerender: {
        routes: ["/blog", "/blog/2022-12-27-my-first-post"],
      },
    }),
  ],
  
}));

Le /blog et /blog/2022-12-27-my-first-post Les itinéraires sont prétendus. Ce que nous voulons, c’est de prétendre tous les articles de blog du répertoire de contenu. Nous allons avoir besoin d’un objet qui charge la liste du contenu et renvoie les URL à la pré-prise.

Ajoutons un objet au routes Config pour présenter le contenu du répertoire de contenu. Mettre à jour le routes Configuration à ce qui suit:

prerender: {
  routes: async () => [
    "/blog",
    {
      contentDir: "src/content/blog",
      transform: (file: PrerenderContentFile) => {
        
        const slug = file.attributes["slug"] || file.name;
        return `/blog/${slug}`;
      },
    },
  ],
},

Le transform La fonction mappe les chemins de fichier vers les URL. La chaîne retournée doit être le chemin d’accès à l’URL de votre application. Le contentDir La valeur est le chemin d’accès au répertoire de contenu, mais il peut également être un modèle glob.

Automatiquement un plan du site

Les sitemaps aident les moteurs de recherche à découvrir votre contenu. L’analogue peut générer automatiquement un point de sitemap lorsque vous activez le sitemap option dans le prerender config. Pour rendre votre blog à découvrir par des moteurs de recherche, activez le sitemap option:

prerender: {
  
  sitemap: {
    host: 'https://pmbanugo.me/',
  },
},

Après avoir construit le site, vous trouverez le plan du site dans le dist/analog/public annuaire.

C’est une enveloppe!

Vous avez maintenant un blog alimenté par Markdown construit avec Angular et complet avec un plan du site. Bien que nous ayons utilisé le style par défaut du modèle, vous pouvez le personnaliser à l’aide de votre bibliothèque d’interface utilisateur préférée. Vous pouvez également améliorer votre blog en créant une voie API vers générer dynamiquement des images graphiques ouvertes pour chaque article de blog.

Vous pouvez copier ou cloner le code source De ce tutoriel pour commencer votre propre blog.

Blogueur heureux! 🚀




Source link
Quitter la version mobile