包详细信息

@metalsmith/markdown

metalsmith18.8kMIT1.10.0

A Metalsmith plugin to render markdown files to HTML

markdown, metalsmith, metalsmith-plugin, static-site

自述文件

@metalsmith/markdown

A Metalsmith plugin to render markdown files to HTML, using Marked (by default).

metalsmith: core plugin npm: version ci: build code coverage license: MIT

Features

  • Compiles .md and .markdown files in metalsmith.source() to HTML.
  • Enables rendering file or metalsmith metadata keys to HTML through the keys option
  • Define a dictionary of markdown globalRefs (for links, images) available to all render targets
  • Supports using the markdown library of your choice through the render option

Installation

NPM:

npm install @metalsmith/markdown

Yarn:

yarn add @metalsmith/markdown

Usage

@metalsmith/markdown is powered by Marked (by default), and you can pass any of the Marked options to it, including the 'pro' options: renderer, tokenizer, walkTokens and extensions.

import markdown from '@metalsmith/markdown'
import hljs from 'highlight.js'

// use defaults
metalsmith.use(markdown())

// use explicit defaults
metalsmith.use({
  wildcard: false,
  keys: [],
  engineOptions: {}
})

// custom
metalsmith.use(
  markdown({
    engineOptions: {
      highlight: function (code) {
        return hljs.highlightAuto(code).value
      },
      pedantic: false,
      gfm: true,
      tables: true,
      breaks: false,
      sanitize: false,
      smartLists: true,
      smartypants: false,
      xhtml: false
    }
  })
)

@metalsmith/markdown provides the following options:

  • keys: Key names of file metadata to render to HTML in addition to its contents - can be nested key paths
  • wildcard (default: false) - Expand * wildcards in keys option keypaths
  • globalRefs - An object of { refname: 'link' } pairs that will be available for all markdown files and keys, or a metalsmith.metadata() keypath containing such object
  • render - Specify a custom render function with the signature (source, engineOptions, context) => string. context is an object with the signature { path:string, key:string } where the path key contains the current file path, and key contains the target metadata key.
  • engineOptions Options to pass to the markdown engine (default marked)

Rendering metadata

You can render markdown to HTML in file or metalsmith metadata keys by specifying the keys option.
The keys option also supports dot-delimited key-paths. You can also use globalRefs within them

metalsmith
  .metadata({
    from_metalsmith_metadata: 'I _shall_ become **markdown** and can even use a [globalref][globalref_link]',
    markdownRefs: {
      globalref_link: 'https://johndoe.com'
    }
  })
  .use(
    markdown({
      keys: {
        files: ['html_desc', 'nested.data'],
        global: ['from_metalsmith_metadata']
      },
      globalRefs: 'markdownRefs'
    })
  )

You can even render all keys at a certain path by setting the wildcard option and using a globstar * in the keypaths.
This is especially useful for arrays like the faq below:

metalsmith.use(
  markdown({
    wildcard: true,
    keys: ['html_desc', 'nested.data', 'faq.*.*']
  })
)

A file page.md with front-matter:

---
html_desc: A **markdown-enabled** _description_
nested:
  data: '#metalsmith'
faq:
  - q: '**Question1?**'
    a: _answer1_
  - q: '**Question2?**'
    a: _answer2_
---

would be transformed into:

{
  "html_desc": "A <strong>markdown-enabled</strong> <em>description</em>\n",
  "nested": {
    "data": "<h1 id=\"metalsmith\">metalsmith</h1>\n"
  },
  "faq": [
    { "q": "<p><strong>Question1?</strong></p>\n", "a": "<p><em>answer1</em></p>\n" },
    { "q": "<p><strong>Question2?</strong></p>\n", "a": "<p><em>answer2</em></p>\n" }
  ]
}

Notes about the wildcard

  • It acts like the single bash globstar. If you specify * this would only match the properties at the first level of the metadata.
  • If a wildcard keypath matches a key whose value is not a string, it will be ignored.
  • It is set to false by default because it can incur some overhead if it is applied too broadly.

Defining a dictionary of markdown globalRefs

Markdown allows users to define links in reference style ([]:).
In a Metalsmith build it may be especially desirable to be able to refer to some links globally. The globalRefs options allows this:

metalsmith.use(
  markdown({
    globalRefs: {
      twitter_link: 'https://twitter.com/johndoe',
      github_link: 'https://github.com/johndoe',
      photo: '/assets/img/me.png'
    }
  })
)

Now contents of any file or metadata key processed by @metalsmith/markdown will be able to refer to these links as [My Twitter][twitter_link] or ![Me][photo]. You can also store the globalRefs object of the previous example in a metalsmith.metadata() key and pass its keypath as globalRefs option instead.

This enables a flow where you can load the refs into global metadata from a source file with @metalsmith/metadata, and use them both in markdown and templating plugins like @metalsmith/layouts:

metalsith
  .metadata({
    global: {
      links: {
        twitter: 'https://twitter.com/johndoe',
        github: 'https://github.com/johndoe'
      }
    }
  })
  // eg in a markdown file: [My Twitter profile][twitter]
  .use(markdown({ globalRefs: 'global.links' }))
  // eg in a handlebars layout: {{ global.links.twitter }}
  .use(layouts({ pattern: '**/*.html' }))

Custom markdown rendering

You can use a custom renderer by using marked.Renderer()

import markdown from '@metalsmith/markdown'
import { marked } from 'marked'
const markdownRenderer = new marked.Renderer()

markdownRenderer.image = function (href, title, text) {
  return `
  <figure>
    <img src="${href}" alt="${title}" title="${title}" />
    <figcaption>
      <p>${text}</p>
    </figcaption>
  </figure>`
}

metalsmith.use(
  markdown({
    engineOptions: {
      renderer: markdownRenderer,
      pedantic: false,
      gfm: true,
      tables: true,
      breaks: false,
      sanitize: false,
      smartLists: true,
      smartypants: false,
      xhtml: false
    }
  })
)

Using another markdown library

If you don't want to use marked, you can use another markdown rendering library through the render option. For example, this is how you could use markdown-it instead:

import MarkdownIt from 'markdown-it'

let markdownIt
metalsmith.use(markdown({
  render(source, opts, context) {
    if (!markdownIt) markdownIt = new MarkdownIt(opts)
    if (context.key == 'contents') return mdIt.render(source)
    return markdownIt.renderInline(source)
  },
  // specify markdownIt options here
  engineOptions: { ... }
}))

Debug

To enable debug logs, set the DEBUG environment variable to @metalsmith/markdown*:

metalsmith.env('DEBUG', '@metalsmith/markdown*')

CLI Usage

Add @metalsmith/markdown key to your metalsmith.json plugins key

{
  "plugins": {
    "@metalsmith/markdown": {
      "engineOptions": {
        "pedantic": false,
        "gfm": true,
        "tables": true,
        "breaks": false,
        "sanitize": false,
        "smartLists": true,
        "smartypants": false,
        "xhtml": false
      }
    }
  }
}

License

MIT

更新日志

Changelog

All notable changes to this project will be documented in this file. Dates are displayed in UTC.

Generated by auto-changelog.

v1.9.2

8 May 2023

  • Fixes missing types and adds source maps to package 78eaefc

v1.9.1

26 February 2023

  • Updates marked from 4.2.4 -> 4.2.12 c9881d1
  • fix: don't log a warning for undefined key values, only when typeof is not string 53feb48
  • fix: don't crash but gracefully ignore undefined for wildcard keypaths d05e39a

v1.9.0

2 February 2023

  • Resolves #65: adds globalRefs option #65
  • Resolves #63: provides a render option allowing usage of any markdown parser. #63
  • Documents the render option and restructures README.md in alignment with other core plugins 2ea44cd

v1.8.0

18 December 2022

  • Resolves #62, deprecates markdown options.<option> in favor of options.engineOptions.<option> #62
  • Provides dual ESM/CJS module a3b6271
  • Adds Typescript support 5ce04b8
  • Updates marked from 4.2.0 -> 4.2.4 fd2fc65
  • Renames default export to markdown for better auto-complete ba9c515

v1.7.0

4 November 2022

  • Drops node < 12 support, updates devDependencies 0727d81
  • Drop support for Metalsmith < 2.5.0 9654d29
  • Better debug logging c9fc051
  • Use metalsmith.debug instead of debug b745991
  • Updates marked from 4.0.16 -> 4.2.0 1aa53d2

v1.6.0

29 May 2022

  • Resolves #60: support nested keypaths for keys option #60
  • Fixes #61: replace Travis CI badge with GH actions in README.md #61
  • Feature: Add support for simple wildcards, get 100% test coverage 9c53cfe
  • Update supported Node version to >=10, update marked 4.0.12 -> 4.0.16 c0d1a86

v1.5.0

21 March 2022

  • chore: update marked@2.1.0 to marked@4.0.12 #57
  • Update debug to ^4.3.4 3b6b861
  • feat: export named plugin b9aaa0f

v1.4.0

12 December 2021

  • Fixed history #45
  • Update packages to address 7 vulnerabilities #43
  • Fixes security vulnerabilities 2c899a7
  • [skip travis] Merge pull request #53 from metalsmith/dependabot/npm_and_yarn/glob-parent-5.1.2 58c695c
  • [skip travis] Merge pull request #52 from metalsmith/dependabot/npm_and_yarn/lodash-4.17.21 45c0362
  • Dropped support for Node <8. Documented 'keys' option in README. Updated dev dependencies baf3422
  • Update packages to address 7 vulnerabilities - minimatch, lodash, and extend deps 3c567c5
  • Aligned dotfiles & default repository files with core metalsmith plugins 0f1cc8f
  • Updated marked to 2.1.0, debug to 4.3.3 149d3d6
  • Add LICENSE file 411e94c
  • Fixes marked incorrect node compat + jsdocs cfb384e
  • Bump glob-parent from 5.1.0 to 5.1.2 808fd6c
  • Bump lodash from 4.17.15 to 4.17.21 e67efeb

1.3.0 - 2019-10-30

  • Updated packages
    • marked v0.7.0
    • eslint
    • eslint-config-prettier
    • eslint-plugin-prettier
    • mocha
    • prettier

1.2.0 - 2019-02-20

  • Docs updated
  • Updated packages
    • debug
    • marked
    • eslint
    • eslint-config-prettier
    • eslint-plugin-prettier
    • mocha
    • prettier

1.1.0 - 2018-10-26

  • Updated packages
    • debug
    • marked
    • eslint
    • eslint-config-prettier
    • eslint-plugin-prettier
    • prettier

1.0.1 - 2018-09-14

  • Added Prettier and ESLint
  • Updated Badges
  • Updated debug package

1.0.0 - 2018-07-17

  • Fixed API
  • Upgraded to Marked 0.4.0 #31
  • Fixed security issue with Buffer #29
  • Ensure key is string #24
  • Cross platform path separators (Windows) #16
  • Strict file endings #10
  • Allow missing keys #9
  • Docs: Usage with highlighting lib #6
  • Updated all packages

0.2.2 - 2018-01-09

  • update marked dependency to fix security issue

0.2.1 - February 6, 2013

  • add debug statements

0.2.0 - February 5, 2013

  • update to use buffers for metalsmith 0.1.0

0.1.0 - February 5, 2013

  • add keys option

0.0.1 - February 4, 2013


:sparkles: