UNPKG

16.1 kBMarkdownView Raw
1# Markdown Magic [![npm-version][npm-badge]][npm-link]
2
3✨ Add a little magic to your markdown ✨
4
5## About
6
7<img align="right" width="200" height="183" src="https://cloud.githubusercontent.com/assets/532272/21507867/3376e9fe-cc4a-11e6-9350-7ec4f680da36.gif">Markdown magic uses comment blocks in markdown files to automatically sync or transform its contents.
8
9- Automatically keep markdown files up to date from local or remote code sources
10- Transform markdown content with custom transform functions
11- Render markdown with any template engine
12- Automatically generate a table of contents
13- ... etc
14
15The comments markdown magic uses are hidden in markdown and when viewed as HTML.
16
17This `README.md` is generated with `markdown-magic` [view the raw file](https://raw.githubusercontent.com/DavidWells/markdown-magic/master/README.md) to see how.
18
19[Video demo](http://www.youtube.com/watch?v=4V2utrvxwJ8) • [Example Repo](https://github.com/DavidWells/repo-using-markdown-magic)
20
21## Table of Contents
22<!-- ⛔️ MD-MAGIC-EXAMPLE:START (TOC:collapse=true&collapseText=Click to expand) -->
23<details>
24<summary>Click to expand</summary>
25
26- [About](#about)
27- [Install](#install)
28- [Usage](#usage)
29 * [API](#api)
30 * [Configuration Options](#configuration-options)
31- [CLI Usage](#cli-usage)
32- [Transforms](#transforms)
33 * [CODE](#code)
34 * [REMOTE](#remote)
35 * [TOC](#toc)
36- [Running Async transforms](#running-async-transforms)
37- [🔌 Third Party Plugins](#%F0%9F%94%8C-third-party-plugins)
38- [Adding Custom Transforms](#adding-custom-transforms)
39- [Plugin Example](#plugin-example)
40- [Other usage examples](#other-usage-examples)
41- [Custom Transform Demo](#custom-transform-demo)
42- [Prior Art](#prior-art)
43- [License](#license)
44- [Usage examples](#usage-examples)
45
46</details>
47<!-- ⛔️ MD-MAGIC-EXAMPLE:END -->
48
49## Install
50
51```bash
52npm install markdown-magic --save-dev
53```
54
55## Usage
56<!-- ⛔️ MD-MAGIC-EXAMPLE:START (CODE:src=./examples/basic-usage.js) -->
57<!-- The below code snippet is automatically added from ./examples/basic-usage.js -->
58```js
59import path from 'path'
60import markdownMagic from 'markdown-magic'
61
62const markdownPath = path.join(__dirname, 'README.md')
63markdownMagic(markdownPath)
64```
65<!-- ⛔️ MD-MAGIC-EXAMPLE:END *-->
66
67
68<!-- ⛔️ MD-MAGIC-EXAMPLE:START (RENDERDOCS:path=./index.js)
69- Do not remove or modify this section -->
70### API
71```js
72markdownMagic(filePath, config, callback)
73```
74- `filePaths` - *String or Array* - Path or glob pattern. Uses [globby patterns](https://github.com/sindresorhus/multimatch/blob/master/test.js)
75- `config` - See configuration options below
76- `callback` - callback to run after markdown updates
77<!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->
78
79<!-- ⛔️ MD-MAGIC-EXAMPLE:START (RENDERDOCS:path=./lib/processFile.js)
80- Do not remove or modify this section -->
81### Configuration Options
82
83- `transforms` - *object* - (optional) Custom commands to transform block contents, see transforms & custom transforms sections below.
84
85- `outputDir` - *string* - (optional) Change output path of new content. Default behavior is replacing the original file
86
87- `matchWord` - *string* - (optional) Comment pattern to look for & replace inner contents. Default `AUTO-GENERATED-CONTENT`
88
89- `DEBUG` - *Boolean* - (optional) set debug flag to `true` to inspect the process
90<!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->
91
92## CLI Usage
93
94You can use `markdown-magic` as a CLI command. Run `markdown --help` to see all available CLI options
95
96```bash
97markdown --help
98# or
99md-magic
100```
101
102This is useful for adding the package quickly to your `package.json` npm scripts
103
104CLI usage example with options
105
106```bash
107md-magic --path '**/*.md' --config ./config.file.js
108```
109
110In NPM scripts, `npm run docs` would run the markdown magic and parse all the `.md` files in the directory.
111
112```json
113"scripts": {
114 "docs": "md-magic --path '**/*.md' --ignore 'node_modules'"
115},
116```
117
118If you have a `markdown.config.js` file where `markdown-magic` is invoked, it will automatically use that as the configuration unless otherwise specified by `--config` flag.
119
120<!-- ⛔️ MD-MAGIC-EXAMPLE:START (CODE:src=./markdown.config.js) -->
121<!-- The below code snippet is automatically added from ./markdown.config.js -->
122```js
123/* CLI markdown.config.js file example */
124module.exports = {
125 matchWord: 'MD-MAGIC-EXAMPLE',
126 transforms: {
127 /* Match <!-- AUTO-GENERATED-CONTENT:START (LOLZ) --> */
128 LOLZ(content, options) {
129 return `This section was generated by the cli config markdown.config.js file`
130 }
131 },
132 callback: function () {
133 console.log('markdown processing done')
134 }
135}
136```
137<!-- ⛔️ MD-MAGIC-EXAMPLE:END *-->
138
139## Transforms
140
141Markdown Magic comes with a couple of built in transforms for you to use or you can extend it with your own transforms. See 'Custom Transforms' below.
142
143<!-- ⛔️ MD-MAGIC-EXAMPLE:START (RENDERDOCS:path=./lib/transforms/index.js) - Do not remove or modify this section -->
144### CODE
145
146Get code from file or URL and put in markdown
147
148**Options:**
149- `src`: The relative path to the code to pull in, or the `URL` where the raw code lives
150- `syntax` (optional): Syntax will be inferred by fileType if not specified
151- `header` (optional): Will add header comment to code snippet. Useful for pointing to relative source directory or adding live doc links
152- `lines` (optional): a range with lines of code which will then be replaced with code from the file. The line range should be defined as: "lines=*startLine*-*EndLine*" (for example: "lines=22-44"). Please see the example below
153
154**Example:**
155```md
156<!-- AUTO-GENERATED-CONTENT:START (CODE:src=./relative/path/to/code.js) -->
157This content will be dynamically replaced with code from the file
158<!-- AUTO-GENERATED-CONTENT:END -->
159```
160
161```md
162 <!-- AUTO-GENERATED-CONTENT:START (CODE:src=./relative/path/to/code.js&lines=22-44) -->
163 This content will be dynamically replaced with code from the file lines 22 through 44
164 <!-- AUTO-GENERATED-CONTENT:END -->
165 ```
166
167Default `MATCHWORD` is `AUTO-GENERATED-CONTENT`
168
169---
170
171### REMOTE
172
173Get any remote Data and put in markdown
174
175**Options:**
176- `url`: The URL of the remote content to pull in
177
178**Example:**
179```md
180<!-- AUTO-GENERATED-CONTENT:START (REMOTE:url=http://url-to-raw-md-file.md) -->
181This content will be dynamically replace from the remote url
182<!-- AUTO-GENERATED-CONTENT:END -->
183```
184
185Default `MATCHWORD` is `AUTO-GENERATED-CONTENT`
186
187---
188
189### TOC
190
191Generate table of contents from markdown file
192
193**Options:**
194- `firsth1` - *boolean* - (optional): Show first h1 of doc in table of contents. Default `false`
195- `collapse` - *boolean* - (optional): Collapse the table of contents in a detail accordian. Default `false`
196- `collapseText` - *string* - (optional): Text the toc accordian summary
197- `excludeText` - *string* - (optional): Text to exclude in the table of contents. Default `Table of Contents`
198
199**Example:**
200```md
201<!-- AUTO-GENERATED-CONTENT:START (TOC) -->
202toc will be generated here
203<!-- AUTO-GENERATED-CONTENT:END -->
204```
205
206Default `MATCHWORD` is `AUTO-GENERATED-CONTENT`
207
208---
209<!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->
210
211
212## Running Async transforms
213
214Markdown magic was designed to work synchronously. Mainly for simplicity & because it's not a serverside app and speed is not really an issue.
215
216You can use async transforms too though! To use async transforms, you will need to force them into a sync mode. [Example](https://github.com/DavidWells/middy-example/blob/7f72fc1afaa8699daf8df77f7d50c0576859b261/scripts/docs.js#L3-L4)
217
218[Forcing async functions to run sync in node.js](https://davidwells.io/snippets/forcing-async-functions-to-sync-in-node/)
219
220Version 2.0 of markdown magic will likely be async first [see issue](https://github.com/DavidWells/markdown-magic/issues/3)
221
222## 🔌 Third Party Plugins
223
224* [wordcount](https://github.com/DavidWells/markdown-magic-wordcount/) - Add wordcount to markdown files
225* [github-contributors](https://github.com/DavidWells/markdown-magic-github-contributors) - List out the contributors of a given repository
226* [directory-tree](https://github.com/camacho/markdown-magic-directory-tree) - Add directory tree to markdown files
227* [install-command](https://github.com/camacho/markdown-magic-install-command) - Add install command to markdown files with `peerDependencies` included
228* [subpackage-list](https://github.com/camacho/markdown-magic-subpackage-list) - Add list of all subpackages (great for projects that use [Lerna](https://github.com/lerna/lerna))
229* [version-badge](https://github.com/camacho/markdown-magic-version-badge) - Add a badge with the latest version of the project
230* [template](https://github.com/camacho/markdown-magic-template) - Add Lodash template support
231* [dependency-table](https://github.com/camacho/markdown-magic-dependency-table) - Add a table of dependencies with links to their repositories, version information, and a short description
232* [package-scripts](https://github.com/camacho/markdown-magic-package-scripts) - Add a table of `package.json` scripts with descriptions
233* [prettier](https://github.com/camacho/markdown-magic-prettier) - Format code blocks with [`prettier`](https://github.com/prettier/prettier)
234* [engines](https://github.com/camacho/markdown-magic-engines) - Print engines list from `package.json`
235* [jsdoc](https://github.com/bradtaylorsf/markdown-magic-jsdoc) - Adds jsdoc comment support
236* [build-badge](https://github.com/rishichawda/markdown-magic-build-badge) - Update branch badges to auto-magically point to current branches.
237* [package-json](https://github.com/forresst/markdown-magic-package-json) - Add the package.json properties to markdown files
238* [local-image](https://github.com/stevenbenisek/markdown-magic-local-image)
239* [figlet](https://github.com/lafourchette/markdown-magic-figlet) - Add FIGfont text to markdown files
240* [local-image](https://github.com/stevenbenisek/markdown-magic-local-image) - plugin to add local images to markdown
241
242## Adding Custom Transforms
243
244Markdown Magic is extendable via plugins.
245
246Plugins allow developers to add new transforms to the `config.transforms` object. This allows for things like using different rendering engines, custom formatting, or any other logic you might want.
247
248Plugins run in order of registration.
249
250The below code is used to generate **this markdown file** via the plugin system.
251
252<!-- ⛔️ MD-MAGIC-EXAMPLE:START (CODE:src=./examples/generate-readme.js) -->
253<!-- The below code snippet is automatically added from ./examples/generate-readme.js -->
254```js
255const fs = require('fs')
256const path = require('path')
257const markdownMagic = require('../index') // 'markdown-magic'
258
259const config = {
260 matchWord: 'MD-MAGIC-EXAMPLE', // default matchWord is AUTO-GENERATED-CONTENT
261 transforms: {
262 /* Match <!-- AUTO-GENERATED-CONTENT:START (customTransform:optionOne=hi&optionOne=DUDE) --> */
263 customTransform(content, options) {
264 console.log('original content in comment block', content)
265 console.log('options defined on transform', options)
266 // options = { optionOne: hi, optionOne: DUDE}
267 return `This will replace all the contents of inside the comment ${options.optionOne}`
268 },
269 /* Match <!-- AUTO-GENERATED-CONTENT:START (RENDERDOCS:path=../file.js) --> */
270 RENDERDOCS(content, options) {
271 const fileContents = fs.readFileSync(options.path, 'utf8')
272 const docBlocs = require('doxxx').parseComments(fileContents, { raw: true, skipSingleStar: true })
273 let updatedContent = ''
274 docBlocs.forEach((data) => {
275 updatedContent += `${data.description.full}\n\n`
276 })
277 return updatedContent.replace(/^\s+|\s+$/g, '')
278 },
279 /* Match <!-- AUTO-GENERATED-CONTENT:START (pluginExample) --> */
280 pluginExample: require('./plugin-example')({ addNewLine: true }),
281 /* Plugins from npm */
282 // count: require('markdown-magic-wordcount'),
283 // github: require('markdown-magic-github-contributors')
284 }
285}
286
287const markdownPath = path.join(__dirname, '..', 'README.md')
288markdownMagic(markdownPath, config, () => {
289 console.log('Docs ready')
290})
291```
292<!-- ⛔️ MD-MAGIC-EXAMPLE:END -->
293
294## Plugin Example
295
296Plugins must return a transform function with the following signature.
297
298```js
299return function myCustomTransform (content, options)
300```
301
302<!-- ⛔️ MD-MAGIC-EXAMPLE:START (CODE:src=./examples/plugin-example.js) -->
303<!-- The below code snippet is automatically added from ./examples/plugin-example.js -->
304```js
305/* Custom Transform Plugin example */
306const merge = require('deepmerge')
307module.exports = function customPlugin(pluginOptions) {
308 // set plugin defaults
309 const defaultOptions = {
310 addNewLine: false
311 }
312 const userOptions = pluginOptions || {}
313 const pluginConfig = merge(defaultOptions, userOptions)
314 // return the transform function
315 return function myCustomTransform (content, options) {
316 const newLine = (pluginConfig.addNewLine) ? '\n' : ''
317 const updatedContent = content + newLine
318 return updatedContent
319 }
320}
321```
322<!-- ⛔️ MD-MAGIC-EXAMPLE:END -->
323
324[View the raw file](https://raw.githubusercontent.com/DavidWells/markdown-magic/master/README.md) file and run `npm run docs` to see this plugin run
325<!-- ⛔️ MD-MAGIC-EXAMPLE:START (pluginExample) DO not edit ⛔️ -->
326This content is altered by the `pluginExample` plugin registered in `examples/generate-readme.js`
327
328<!-- ⛔️ MD-MAGIC-EXAMPLE:END -->
329
330## Other usage examples
331
332- [Serverless Plugin Repo](https://github.com/serverless/plugins/blob/master/generate-docs.js) this example takes a `json` file and converts it into a github flavored markdown table
333- [MochaJS](https://github.com/mochajs/mocha/blob/4cc711fa00f7166a2303b77bf2487d1c2cc94621/scripts/markdown-magic.config.js)
334- [tc39/agendas](https://github.com/tc39/agendas#agendas) - [code](https://github.com/tc39/agendas/blob/65945b1b6658e9829ef95a51bf2632ff44f951e6/scripts/generate.js)
335- [moleculerjs/moleculer-addons](https://github.com/moleculerjs/moleculer-addons/blob/7cf0f72140717c52621b724cd54a710517106df0/readme-generator.js)
336- [good-first-issue](https://github.com/bnb/good-first-issue/blob/e65513a1f26167dea3c137008b8796640d8d5303/markdown.config.js)
337- [navikt/nav-frontend-moduler](https://github.com/navikt/nav-frontend-moduler/blob/20ad521c27a43d3203eab4bc32121e5b8270c077/_scripts/generateReadmes.js)
338- [country-flags-svg](https://github.com/ronatskiy/country-flags-svg/blob/cfb2368c7e634ebc1679855e13cc3e26ca11187f/markdown.config.js)
339- [react-typesetting](https://github.com/exogen/react-typesetting/blob/7114cdc8c4cb1b0d59ebc8b5364e808687419889/markdown.config.js)
340- [and many more!](https://github.com/search?o=desc&p=1&q=markdown-magic+filename%3Apackage.json+-user%3Ah13i32maru+-user%3Aesdoc+-user%3Aes-doc&s=indexed&type=Code)
341
342## Custom Transform Demo
343
344View the raw source of this `README.md` file to see the comment block and see how the `customTransform` function in `examples/generate-readme.js` works
345
346<!-- ⛔️ MD-MAGIC-EXAMPLE:START (customTransform:optionOne=hi&optionOne=DUDE) - Do not remove or modify this section -->
347This will replace all the contents of inside the comment DUDE
348<!-- ⛔️ MD-MAGIC-EXAMPLE:END - Do not remove or modify this section -->
349
350## Prior Art
351
352This was inspired by [Kent C Dodds](https://twitter.com/kentcdodds) and [jfmengels](https://github.com/jfmengels)'s [all contributors cli](https://github.com/jfmengels/all-contributors-cli) project.
353
354<!-- MD-MAGIC-EXAMPLE:START (LOLZ)-->
355This section was generated by the cli config markdown.config.js file
356<!-- MD-MAGIC-EXAMPLE:END (LOLZ)-->
357
358## License
359
360[MIT][mit] © [DavidWells][author]
361
362[npm-badge]:https://img.shields.io/npm/v/markdown-magic.svg?style=flat-square
363[npm-link]: http://www.npmjs.com/package/markdown-magic
364[mit]: http://opensource.org/licenses/MIT
365[author]: http://github.com/davidwells
366
367## Usage examples
368
369- [Project using markdown-magic](https://github.com/search?o=desc&q=filename%3Apackage.json+%22markdown-magic%22&s=indexed&type=Code)
370- [Examples in md](https://github.com/search?l=Markdown&o=desc&q=AUTO-GENERATED-CONTENT&s=indexed&type=Code)