mirror of
https://github.com/kremalicious/astro-redirect-from.git
synced 2024-12-22 09:23:21 +01:00
prototype 🏗️
This commit is contained in:
commit
a98a07be8c
10
.editorconfig
Normal file
10
.editorconfig
Normal file
@ -0,0 +1,10 @@
|
||||
# editorconfig.org
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
end_of_line = lf
|
||||
indent_size = 2
|
||||
indent_style = space
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
10
.eslintrc.json
Normal file
10
.eslintrc.json
Normal file
@ -0,0 +1,10 @@
|
||||
{
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"plugins": ["@typescript-eslint", "prettier"],
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier"
|
||||
],
|
||||
"rules": {}
|
||||
}
|
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
node_modules
|
||||
.yarnclean
|
||||
.cache
|
||||
coverage
|
||||
.env
|
||||
.env.local
|
||||
.env.development
|
||||
.nova
|
||||
|
||||
# build output
|
||||
dist/
|
7
.prettierrc.json
Normal file
7
.prettierrc.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "none",
|
||||
"tabWidth": 2,
|
||||
"endOfLine": "lf"
|
||||
}
|
9
LICENSE
Normal file
9
LICENSE
Normal file
@ -0,0 +1,9 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2008-2018 Matthias Kretschmann
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
213
README.md
Normal file
213
README.md
Normal file
@ -0,0 +1,213 @@
|
||||
[![astro-redirect-from](https://raw.githubusercontent.com/kremalicious/astro-redirect-from/main/src/astro-redirect-from.png)](https://kremalicious.com/astro-redirect-from/)
|
||||
|
||||
# astro-redirect-from
|
||||
|
||||
[![npm package](https://img.shields.io/npm/v/astro-redirect-from.svg)](https://www.npmjs.com/package/astro-redirect-from)
|
||||
[![Build Status](https://github.com/kremalicious/astro-redirect-from/workflows/CI/badge.svg)](https://github.com/kremalicious/astro-redirect-from/actions)
|
||||
[![Maintainability](https://api.codeclimate.com/v1/badges/9643b2a038a7d338a73a/maintainability)](https://codeclimate.com/github/kremalicious/astro-redirect-from/maintainability)
|
||||
[![Coverage](https://api.codeclimate.com/v1/badges/9643b2a038a7d338a73a/test_coverage)](https://codeclimate.com/github/kremalicious/astro-redirect-from/test_coverage)
|
||||
|
||||
> 🎯 Set redirect urls in your frontmatter within your [Astro](https://astro.build) site's Markdown files. Mimics the behavior of [jekyll-redirect-from](https://github.com/jekyll/jekyll-redirect-from) and [gatsby-redirect-from](https://kremalicious.com/gatsby-redirect-from/).
|
||||
>
|
||||
> https://kremalicious.com/astro-redirect-from/
|
||||
|
||||
---
|
||||
|
||||
Allows you to manage redirects directly from your Markdown files' frontmatter.
|
||||
|
||||
**Table of Contents**
|
||||
|
||||
- [How it Works](#how-it-works)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Installation](#installation)
|
||||
- [Options](#options)
|
||||
- [`contentDir: string`](#contentdir-string)
|
||||
- [`getSlug: (filePath: string) => string`](#getslug-filepath-string--string)
|
||||
- [Usage](#usage)
|
||||
- [Plugin Development](#plugin-development)
|
||||
- [Changelog](#changelog)
|
||||
- [License](#license)
|
||||
|
||||
---
|
||||
|
||||
Imagine you've just revamped your blog, and some of your old URLs have changed. You don't want to lose the SEO juice, nor do you want to leave your readers with broken links. This is where redirects come into play. But managing redirects can be cumbersome, especially if you have to do it manually or through server configurations.
|
||||
|
||||
This plugin automates this process by reading the `redirect_from` field in the frontmatter of your Markdown files and updating Astro's configuration to handle these redirects automatically.
|
||||
|
||||
## How it Works
|
||||
|
||||
By adding a `redirect_from` list in your Markdown frontmatter, the plugin integrates these redirects into Astro's [`redirects`](https://docs.astro.build/en/reference/configuration-reference/#redirects) configuration automatically, whether you're running the development server or building your project.
|
||||
|
||||
The plugin operates during the [`astro:config:setup`](https://docs.astro.build/en/reference/integrations-reference/#astroconfigsetup) lifecycle hook. It scans all Markdown files for the `redirect_from` key and updates Astro's configuration using [`updateConfig()`](https://docs.astro.build/en/reference/integrations-reference/#updateconfig-option). This ensures that any existing redirects are merged with new ones generated by the plugin.
|
||||
|
||||
Astro takes over from there, handling the redirects based on your site's build mode and in combination with any other integrations you might be using:
|
||||
|
||||
> For statically-generated sites with no adapter installed, this will produce a client redirect using a `<meta http-equiv="refresh">` tag and does not support status codes.
|
||||
>
|
||||
> When using SSR or with a static adapter in `output: static` mode, status codes are supported. Astro will serve redirected GET requests with a status of 301 and use a status of 308 for any other request method.
|
||||
> [Astro Configuration Reference: redirects](https://docs.astro.build/en/reference/configuration-reference/#redirects)
|
||||
|
||||
The plugin is designed to work with various hosting integrations, where most of them generate further redirect files in the places they require so this plugin works in combination with them:
|
||||
|
||||
- [ ] Netlify
|
||||
- [ ] Vercel
|
||||
- [ ] Cloudflare
|
||||
- [ ] S3
|
||||
|
||||
Because Astro integrations are run in the order they are defined in Astro's `integrations` array, this plugin should come before any other integrations which make use of the `redirects` config.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
The plugin is designed to work without configuration, especially if your project aligns with Astro's default settings.
|
||||
|
||||
- Requires Astro v3 (v2 probably works too, but is not tested)
|
||||
- Markdown files should be in a directory (default is `src/pages/`)
|
||||
- Slugs are extracted either from the frontmatter or the file/folder path
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
cd yourproject/
|
||||
|
||||
# Using NPM
|
||||
npx astro add astro-redirect-from
|
||||
# Using Yarn
|
||||
yarn astro add astro-redirect-from
|
||||
# Using PNPM
|
||||
pnpm astro add astro-redirect-from
|
||||
```
|
||||
|
||||
If installing manually:
|
||||
|
||||
```bash
|
||||
npm i astro-redirect-from
|
||||
```
|
||||
|
||||
Then load the plugin in your Astro config file:
|
||||
|
||||
```js title="astro.config.mjs"
|
||||
import { defineConfig } from 'astro/config'
|
||||
import redirectFrom from 'astro-redirect-from'
|
||||
|
||||
export default defineConfig({
|
||||
// ...
|
||||
integrations: [
|
||||
// make sure this is listed before any
|
||||
// hosting integration
|
||||
redirectFrom()
|
||||
]
|
||||
// ...
|
||||
)}
|
||||
```
|
||||
|
||||
That's it. Your redirects will be automatically added the next time you run `astro dev` or `astro build`. If any of them have a `redirect_from` field, that is.
|
||||
|
||||
[See Usage](#usage)
|
||||
|
||||
### Options
|
||||
|
||||
Options are all optional and can be passed in Astro's config file:
|
||||
|
||||
```js title="astro.config.mjs"
|
||||
import { defineConfig } from 'astro/config'
|
||||
import redirectFrom from 'astro-redirect-from'
|
||||
import { getMySlug } from './your-slug-function'
|
||||
|
||||
export default defineConfig({
|
||||
// ...
|
||||
integrations: [
|
||||
redirectFrom({
|
||||
contentDir: './content',
|
||||
getSlug: getMySlug
|
||||
})
|
||||
]
|
||||
// ...
|
||||
)}
|
||||
```
|
||||
|
||||
#### `contentDir: string`
|
||||
|
||||
_Default: `src/pages/`_
|
||||
|
||||
Specify a different directory for your Markdown files, relative to the project root.
|
||||
|
||||
#### `getSlug: (filePath: string) => string`
|
||||
|
||||
_Default: `getSlugFromFilePath()`, see below_
|
||||
|
||||
If you need a custom slug structure, pass a function to construct your slug from the file path.
|
||||
|
||||
If you use a `slug` field in your frontmatter, this will be preferred by the plugin and passing any `getSlug` function will have no effect in that case.
|
||||
|
||||
The default function is a great starting point:
|
||||
|
||||
```typescript
|
||||
function getSlugFromFilePath(filePath: string) {
|
||||
const parsedPath = path.parse(filePath)
|
||||
let slug
|
||||
|
||||
// construct slug as full path from either:
|
||||
// - file name, or
|
||||
// - folder name if file name is index.md
|
||||
if (parsedPath.base === 'index.md' || parsedPath.base === 'index.mdx') {
|
||||
slug = `/${parsedPath.dir}`
|
||||
} else {
|
||||
slug = `/${parsedPath.dir}/${parsedPath.name}`
|
||||
}
|
||||
|
||||
return slug
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
In your Markdown file's YAML frontmatter, use the key `redirect_from` followed by a list.
|
||||
|
||||
```yaml
|
||||
---
|
||||
redirect_from:
|
||||
- /old-url-1
|
||||
- /old-url-2
|
||||
- /old-url-3.html
|
||||
---
|
||||
```
|
||||
|
||||
## Plugin Development
|
||||
|
||||
```bash
|
||||
npm i
|
||||
npm start
|
||||
|
||||
# production build
|
||||
npm run build
|
||||
|
||||
# publishing to npm & GitHub releases
|
||||
# uses https://github.com/webpro/release-it
|
||||
npm run release
|
||||
```
|
||||
|
||||
## Changelog
|
||||
|
||||
See [CHANGELOG.md](CHANGELOG.md).
|
||||
|
||||
## License
|
||||
|
||||
The MIT License
|
||||
|
||||
Copyright (c) 2023 Matthias Kretschmann
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
Made with ♥ by [Matthias Kretschmann](https://matthiaskretschmann.com) ([@kremalicious](https://github.com/kremalicious))
|
||||
|
||||
Say thanks with BTC:
|
||||
`35UUssHexVK48jbiSgTxa4QihEoCqrwCTG`
|
||||
|
||||
Say thanks with ETH:
|
||||
`krema.eth`
|
7343
package-lock.json
generated
Normal file
7343
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
36
package.json
Normal file
36
package.json
Normal file
@ -0,0 +1,36 @@
|
||||
{
|
||||
"name": "astro-redirect-from",
|
||||
"version": "0.1.0",
|
||||
"description": "🎯 Set redirect urls in your frontmatter within your Astro site's Markdown files. ",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/kremalicious/astro-redirect-from.git"
|
||||
},
|
||||
"keywords": [
|
||||
"astro-integration"
|
||||
],
|
||||
"author": "Matthias Kretschmann <m@kretschmann.io>",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/kremalicious/astro-redirect-from/issues"
|
||||
},
|
||||
"homepage": "https://kremalicious.com/astro-redirect-from",
|
||||
"type": "module",
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.6.3",
|
||||
"eslint": "^8.49.0",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"prettier": "^3.0.3",
|
||||
"typescript": "^5.2.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^3.1.2",
|
||||
"fast-glob": "^3.3.1",
|
||||
"gray-matter": "^4.0.3"
|
||||
}
|
||||
}
|
81
src/index.ts
Normal file
81
src/index.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import fs from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import fg from 'fast-glob'
|
||||
import matter from 'gray-matter'
|
||||
import type { AstroIntegration, AstroIntegrationLogger } from 'astro'
|
||||
import { getSlugFromFilePath, writeJson } from './utils'
|
||||
|
||||
type PluginOptions = {
|
||||
contentDir?: string
|
||||
getSlug?: (filePath: string) => string
|
||||
}
|
||||
|
||||
export default function astroRedirectFrom({
|
||||
contentDir = 'src/pages/',
|
||||
getSlug = getSlugFromFilePath
|
||||
}: PluginOptions = {}): AstroIntegration {
|
||||
const sourceDir = path.join(process.cwd(), contentDir)
|
||||
|
||||
return {
|
||||
name: 'redirect-from',
|
||||
hooks: {
|
||||
'astro:config:setup': async ({
|
||||
updateConfig,
|
||||
logger
|
||||
}: {
|
||||
updateConfig: (newConfig: Record<string, any>) => void
|
||||
logger: AstroIntegrationLogger
|
||||
}) => {
|
||||
const redirects: { [old: string]: string } = {}
|
||||
|
||||
try {
|
||||
const markdownFiles = await fg.glob('./**/*.{md,mdx}', {
|
||||
cwd: sourceDir
|
||||
})
|
||||
if (!markdownFiles?.length) {
|
||||
logger.warn('No markdown files found')
|
||||
return
|
||||
}
|
||||
|
||||
for (const markdownFile of markdownFiles) {
|
||||
const fileContent = await fs.readFile(
|
||||
path.join(sourceDir, markdownFile),
|
||||
'utf-8'
|
||||
)
|
||||
|
||||
const { data: frontmatter } = matter(fileContent)
|
||||
const postRedirectFrom: string[] = frontmatter?.redirect_from
|
||||
if (
|
||||
!frontmatter ||
|
||||
!postRedirectFrom ||
|
||||
// filter out drafts in production
|
||||
(import.meta.env.PROD && frontmatter.draft === true)
|
||||
)
|
||||
continue
|
||||
|
||||
let postSlug = frontmatter.slug
|
||||
if (!postSlug) postSlug = getSlug(markdownFile)
|
||||
if (!postSlug) continue
|
||||
|
||||
for (const slug of postRedirectFrom) {
|
||||
redirects[slug] = postSlug
|
||||
}
|
||||
}
|
||||
|
||||
updateConfig({ redirects })
|
||||
|
||||
await writeJson(
|
||||
path.join(process.cwd(), '.astro', 'redirect_from.json'),
|
||||
redirects
|
||||
)
|
||||
|
||||
logger.info(
|
||||
`Added ${Object.keys(redirects).length} redirects to Astro config`
|
||||
)
|
||||
} catch (error: any) {
|
||||
logger.error((error as Error).message)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
25
src/utils.ts
Normal file
25
src/utils.ts
Normal file
@ -0,0 +1,25 @@
|
||||
import path from 'node:path'
|
||||
import fs from 'node:fs/promises'
|
||||
import type { PathLike } from 'node:fs'
|
||||
|
||||
export function getSlugFromFilePath(filePath: string) {
|
||||
const parsedPath = path.parse(filePath)
|
||||
let slug
|
||||
|
||||
// construct slug as full path from either:
|
||||
// - file name, or
|
||||
// - folder name if file name is index.md
|
||||
if (parsedPath.base === 'index.md' || parsedPath.base === 'index.mdx') {
|
||||
slug = `/${parsedPath.dir}`
|
||||
} else {
|
||||
slug = `/${parsedPath.dir}/${parsedPath.name}`
|
||||
}
|
||||
|
||||
return slug
|
||||
}
|
||||
|
||||
export async function writeJson<T>(path: PathLike, data: T) {
|
||||
await fs.writeFile(path, JSON.stringify(data, null, '\t'), {
|
||||
encoding: 'utf-8'
|
||||
})
|
||||
}
|
9
tsconfig.json
Normal file
9
tsconfig.json
Normal file
@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules"],
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"typeRoots": ["node_modules/@types"]
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user