高级功能
本页面介绍 astro-smart-links 的高级用法:自定义链接结构、链接转换与完整配置。每个预览区都是该配置的真实输出。
自定义链接结构
Section titled “自定义链接结构”用 wrapperTemplate 完全控制链接的 HTML 结构。回调收到 (node, type, meta),返回替换后的节点;meta.className 是当前类型配置的类名:
自定义链接结构
import { smartLinks } from 'astro-smart-links';import { h } from 'hastscript';
smartLinks({ wrapperTemplate: (node, type, meta) => { const icons = { internal: ['after', '📄'], external: ['after', '🔗'], broken: ['before', '⚠️'], }; const [position, icon] = icons[type];
if (position === 'before') { node.children.unshift(h('span', { className: 'mr-1' }, icon)); } else { node.children.push(h('span', { className: 'ml-1' }, icon)); }
node.properties.className = [ ...(node.properties.className || []), meta.className, 'flex', 'items-center', 'gap-1', ];
return node; },}),在链接末尾追加标签,直观标注链接类型:
添加徽章
import { smartLinks } from 'astro-smart-links';import { h } from 'hastscript';
smartLinks({ wrapperTemplate: (node, type, meta) => { const badges = { internal: ['badge badge-primary badge-sm', '内部'], external: ['badge badge-secondary badge-sm', '外部'], broken: ['badge badge-error badge-sm', '失效'], }; const [className, label] = badges[type];
node.children.push(h('span', { className }, label)); node.properties.className = [ ...(node.properties.className || []), meta.className, 'flex', 'items-center', 'gap-2', ];
return node; },}),customInternalLinkTransform、customExternalLinkTransform 与 customBrokenLinkTransform 按类型修改节点,回调收到 (node, meta)。自定义转换会完全接管该类型,因此需要自己应用 meta.className:
链接转换
import { smartLinks } from 'astro-smart-links';
smartLinks({ customInternalLinkTransform: (node, meta) => { node.properties.className = [...(node.properties.className || []), meta.className]; if (meta.pathname?.includes('demo')) { node.properties['data-section'] = 'demos'; } }, customExternalLinkTransform: (node, meta) => { node.properties.className = [...(node.properties.className || []), meta.className]; node.properties.target = '_blank'; node.properties.rel = 'noopener noreferrer'; node.properties['data-external'] = 'true';
if (meta.href.includes('github.com')) { node.properties.className.push('github-link'); } }, customBrokenLinkTransform: (node, meta) => { node.properties.className = [...(node.properties.className || []), meta.className]; node.properties['data-error'] = 'true'; node.properties.title = '此页面不存在'; },}),被 ignore 命中的链接不会做任何处理:不添加类名、不设置 target/rel、不追加图标,也不参与断链检查。其余链接照常处理:
忽略链接
import { smartLinks } from 'astro-smart-links';
smartLinks({ // 正则同时匹配中文与英文路径,如 /draft/ 与 /en/draft/ ignore: [/\/draft\//, /\/preview\//],}),组合常用选项的完整示例:
完整配置示例
import { defineConfig } from 'astro/config';import { smartLinks } from 'astro-smart-links';
export default defineConfig({ integrations: [ smartLinks({ internalLinkClass: 'internal-link', externalLinkClass: 'external-link', brokenLinkClass: 'broken-link', target: '_blank', rel: 'noopener noreferrer', ignore: ['/draft/'],
// 断链处理 failOnBroken: true, reportFile: '.smart-links-report.json', }), ],});继续浏览: