- Published on
Introducing Tailwind Nextjs Starter Blog
date: 2021-01-12 → mod: 2023-11-04
ちょっと追記したよ🤩
Tailwind Nextjs Starter Blog
This is a Next.js, Tailwind CSS blogging starter template. Probably the most feature-rich Next.js markdown blogging template out there. Comes out of the box configured with the latest technologies to make technical writing a breeze. Easily configurable and customizable. Perfect as a replacement to existing Jekyll and Hugo individual blogs.
Check out the documentation below to get started.
Facing issues? Check the FAQ page and do a search on past issues. Feel free to open a new issue if none has been posted previously.
Feature request? Check the past discussions to see if it has been brought up previously. Otherwise, feel free to start a new discussion thread. All ideas are welcomed!
Examples
Demo Blog - this repo
My personal blog - modified to auto-generate blog posts with dates
- ちょっと何がどう変わっているのかが分からなかった....
Aloisdg's cookbook - with pictures and recipes!
GautierArcin's demo with next translate - includes translation of mdx posts, source code
- 画面右上で言語を切り替えられる!!!記事のファイル名に
.ja.mdx
って間に言語を入れればあらかじめ作っておいたファイルに切り替わる!
- 画面右上で言語を切り替えられる!!!記事のファイル名に
David Levai's digital garden - customized design and added email subscriptions
- ほとんどブログは書いてないっぽいけど、自分の出し方がすごく参考になる。画面右上にselectタイプの検索機能もあって面白い!
Thinh's Corner - customized layout with sticky side table of contents
- 目次機能がもうなくなっちゃってるけど、アーカイブされたコードはまだ残ってるからメモしとくと...
function TocComponent({ toc }) { const [activeId, setActiveId] = useState(); useIntersectionObserver(setActiveId); const [TOC, setTOC] = useState([]); useEffect(() => { let etoc = toc.map((e) => ({ ...e, children: [] })); for (let i = etoc.length - 1; i >= 0; i--) { if (etoc[i].depth == 1) continue; for (let j = i; j >= 0; j--) { if (etoc[i].depth - etoc[j].depth == 1) { etoc[j].children.unshift(etoc[i]); break; } } } setTOC(etoc.filter((e) => e.depth == 1)); }, [toc]); let RenderToc = ({ item, activeId }) => { const isActive = (e) => { if ("#" + activeId === e.url) return true; for (let i of e.children) if (isActive(i)) return true; return false; }; return item.map((e, i) => ( <div key={i}> <Link href={e.url}> <p className={`pl-2 border-l-[3px] ${ isActive(e) && "border-primary-500 text-primary-600" }`} > {e.value} </p> </Link> {isActive(e) && e.children.length > 0 && ( <div className="mt-1 ml-4 space-y-1"> <RenderToc item={e.children} activeId={activeId} /> </div> )} </div> )); }; return ( <div className="mt-5 space-y-1 text-sm"> <p className="text-lg font-bold">Table of content</p> <RenderToc item={TOC} activeId={activeId} /> </div> ); }
んで、この
useIntersectionObserver
関数の中身が....const useIntersectionObserver = (setActiveId) => { const headingElementsRef = useRef({}); useEffect(() => { const callback = (headings) => { headingElementsRef.current = headings.reduce((map, headingElement) => { map[headingElement.target.id] = headingElement; return map; }, headingElementsRef.current); const visibleHeadings = []; Object.keys(headingElementsRef.current).forEach((key) => { const headingElement = headingElementsRef.current[key]; if (headingElement.isIntersecting) visibleHeadings.push(headingElement); }); const getIndexFromId = (id) => headingElements.findIndex((heading) => heading.id === id); if (visibleHeadings.length === 1) { setActiveId(visibleHeadings[0].target.id); } else if (visibleHeadings.length > 1) { const sortedVisibleHeadings = visibleHeadings.sort( (a, b) => getIndexFromId(a.target.id) > getIndexFromId(b.target.id) ); setActiveId(sortedVisibleHeadings[0].target.id); } }; const observer = new IntersectionObserver(callback, { rootMargin: "0px 0px -40% 0px", }); const headingElements = Array.from(document.querySelectorAll("h1, h2, h3")); headingElements.forEach((element) => observer.observe(element)); return () => observer.disconnect(); }, [setActiveId]); };
あと、タイトルのところに文字数と目安時間が書いてあるのが気になった。 どこからつなげているのかが謎....。importの記述にないし。。。。
export default function PostLayout({ frontMatter, authorDetails, next, prev, children, toc }) { const { slug, fileName, date, title, tags, readingTime } = frontMatter; return ( <div> <span> {readingTime.words} words </span> <span> {readingTime.text} </span> </div> )}
Using the template? Feel free to create a PR and add your blog to this list.
Motivation
I wanted to port my existing blog to Nextjs and Tailwind CSS but there was no easy out of the box template to use so I decided to create one. Design is adapted from Tailwindlabs blog.
I wanted it to be nearly as feature-rich as popular blogging templates like beautiful-jekyll and Hugo Academic but with the best of React's ecosystem and current web development's best practices.
ブログをもともともってて、Next.jsやTailwindに引っ越したいけど簡単にはできないから、Tailwindブログをベースに作られたのが、このリポだったのね👀
機能も充実している人気のあるブログのテンプレートに近づけたかったし、Reactのエコシステムをいい感じに使ったり、web開発のちょうどいい練習にもしたかったっていうことか....📝
最新の技術に触れながらブログを改造し続けたい欲のある私にはもってこいなのかもしれない🔥
Features
- Easy styling customization with Tailwind 3.0 and primary color attribute
- Near perfect lighthouse score - Lighthouse report
- Lightweight, 45kB first load JS, uses Preact in production build
- Mobile-friendly view
- Light and dark theme
- Self-hosted font with Fontsource
- Supports plausible, simple analytics and google analytics
- MDX - write JSX in markdown documents!
- Server-side syntax highlighting with line numbers and line highlighting via rehype-prism-plus
- Math display supported via KaTeX
- Citation and bibliography support via rehype-citation
- Automatic image optimization via next/image
- Flexible data retrieval with mdx-bundler
- Support for tags - each unique tag will be its own page
- Support for multiple authors
- Blog templates
- TOC component
- Support for nested routing of blog posts
- Newsletter component with support for mailchimp, buttondown and convertkit
- Supports giscus, utterances or disqus
- Projects page
- Preconfigured security headers
- SEO friendly with RSS feed, sitemaps and more!
Sample posts
- A markdown guide
- Learn more about images in Next.js
- A tour of math typesetting
- Simple MDX image grid
- Example of long prose
- Example of Nested Route Post
Quick Start Guide
- JS (official support) -
npx degit https://github.com/timlrx/tailwind-nextjs-starter-blog.git
or TS (community support) -npx degit timlrx/tailwind-nextjs-starter-blog#typescript
- Personalize
siteMetadata.js
(site related information) - Modify the content security policy in
next.config.js
if you want to use any analytics provider or a commenting solution other than giscus. - Personalize
authors/default.md
(main author) - Modify
projectsData.ts
- Modify
headerNavLinks.ts
to customize navigation links - Add blog posts
- Deploy on Vercel
Development
First, run the development server:
npm start
# or
npm run dev
Open http://localhost:3000 with your browser to see the result.
You can start editing the page by modifying pages/index.js
. The page auto-updates as you edit the file.
Extend / Customize
とりあえず、いじってみたことをTodoリストにしてみたw
data/siteMetadata.js
- contains most of the site related information which should be modified for a user's need.data/authors/default.md
- default author information (required). Additional authors can be added as files indata/authors
.data/projectsData.js
- data used to generate styled card on the projects page.data/headerNavLinks.js
- navigation links.data/logo.svg
- replace with your own logo.data/blog
- replace with your own blog posts.public/static
- store assets such as images and favicons.tailwind.config.js
andcss/tailwind.css
- contain the tailwind stylesheet which can be modified to change the overall look and feel of the site.css/prism.css
- controls the styles associated with the code blocks. Feel free to customize it and use your preferred prismjs theme e.g. prism themes.components/social-icons
- to add other icons, simply copy an svg file from Simple Icons and map them inindex.js
. Other icons use heroicons.components/MDXComponents.js
- pass your own JSX code or React component by specifying it over here. You can then call them directly in the.mdx
or.md
file. By default, a custom link and image component is passed.layouts
- main templates used in pages.pages
- pages to route to. Read the Next.js documentation for more information.next.config.js
- configuration related to Next.js. You need to adapt the Content Security Policy if you want to load scripts, images etc. from other domains.
Post
Frontmatter
Frontmatter follows Hugo's standards.
Currently 10 fields are supported.
title (required)
date (required)
tags (required, can be empty array)
lastmod (optional)
draft (optional)
summary (optional)
images (optional, if none provided defaults to socialBanner in siteMetadata config)
authors (optional list which should correspond to the file names in `data/authors`. Uses `default` if none is specified)
layout (optional list which should correspond to the file names in `data/layouts`)
canonicalUrl (optional, canonical url for the post for SEO)
Here's an example of a post's frontmatter:
---
title: 'Introducing Tailwind Nexjs Starter Blog'
date: '2021-01-12'
lastmod: '2021-01-18'
tags: ['next-js', 'tailwind', 'guide']
draft: false
summary: 'Looking for a performant, out of the box template, with all the best in web technology to support your blogging needs? Checkout the Tailwind Nextjs Starter Blog template.'
images: ['/static/images/canada/mountains.jpg', '/static/images/canada/toronto.jpg']
authors: ['default', 'sparrowhawk']
layout: PostLayout
canonicalUrl: https://tailwind-nextjs-starter-blog.vercel.app/blog/introducing-tailwind-nextjs-starter-blog
---
Compose
Run node ./scripts/compose.js
to bootstrap a new post.
Follow the interactive prompt to generate a post with pre-filled front matter.
Deploy
Vercel
The easiest way to deploy the template is to use the Vercel Platform from the creators of Next.js. Check out the Next.js deployment documentation for more details.
Netlify / GitHub Pages / Firebase etc.
As the template uses next/image
for image optimization, additional configurations have to be made to deploy on other popular static hosting websites like Netlify or GitHub Pages. An alternative image optimization provider such as Imgix, Cloudinary or Akamai has to be used. Alternatively, replace the next/image
component with a standard <img>
tag. See next/image
documentation for more details.
The API routes used in the newsletter component cannot be used in a static site export. You will need to use a form API endpoint provider and substitute the route in the newsletter component accordingly. Other hosting platforms such as Netlify also offer alternative solutions - please refer to their docs for more information.
Support
Using the template? Support this effort by giving a star on GitHub, sharing your own blog and giving a shoutout on Twitter or be a project sponsor.