• Stars
    star
    785
  • Rank 57,743 (Top 2 %)
  • Language
    JavaScript
  • Created almost 8 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

💫  Automatically format markdown files using comment blocks. Update contents via custom transforms, external data sources & your source code.

Markdown Magic npm-version

✨ Add a little magic to your markdown ✨

About

Markdown magic uses comment blocks in markdown files to automatically sync or transform its contents.

  • Automatically keep markdown files up to date from local or remote code sources
  • Transform markdown content with custom transform functions
  • Render markdown with any template engine
  • Automatically generate a table of contents
  • ... etc

The comments markdown magic uses are hidden in markdown and when viewed as HTML.

This README.md is generated with markdown-magic view the raw file to see how.

Video demoExample Repo

Table of Contents

Click to expand

Install

npm install markdown-magic --save-dev

Usage

import path from 'path'
import markdownMagic from 'markdown-magic'

const markdownPath = path.join(__dirname, 'README.md')
markdownMagic(markdownPath)

API

Markdown Magic

Configuration Options

  • transforms - object - (optional) Custom commands to transform block contents, see transforms & custom transforms sections below.

  • outputDir - string - (optional) Change output path of new content. Default behavior is replacing the original file

  • matchWord - string - (optional) Comment pattern to look for & replace inner contents. Default AUTO-GENERATED-CONTENT

  • DEBUG - Boolean - (optional) set debug flag to true to inspect the process

CLI Usage

You can use markdown-magic as a CLI command. Run markdown --help to see all available CLI options

markdown --help
# or
md-magic

This is useful for adding the package quickly to your package.json npm scripts

CLI usage example with options

md-magic --path '**/*.md' --config ./config.file.js

In NPM scripts, npm run docs would run the markdown magic and parse all the .md files in the directory.

"scripts": {
  "docs": "md-magic --path '**/*.md' --ignore 'node_modules'"
},

If 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.

/* CLI markdown.config.js file example */
module.exports = {
  // handleOutputPath: (currentPath) => {
  //   const newPath =  'x' + currentPath
  //   return newPath
  // },
  // handleOutputPath: (currentPath) => {
  //   const newPath = currentPath.replace(/fixtures/, 'fixtures-out')
  //   return newPath
  // },
  transforms: {
    /* Match <!-- AUTO-GENERATED-CONTENT:START (transformOne) --> */
    transformOne() {
      return `This section was generated by the cli config md.config.js file`
    },
    functionName() {
      return `xyz`
    }
  }
}

Transforms

Markdown 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.

> TOC

Generate taxxxxble of contents from markdown file

Options:

  • firsth1 - boolean - (optional): Show first h1 of doc in table of contents. Default false
  • collapse - boolean - (optional): Collapse the table of contents in a detail accordian. Default false
  • collapseText - string - (optional): Text the toc accordian summary
  • excludeText - string - (optional): Text to exclude in the table of contents. Default Table of Contents
  • maxDepth - number - (optional): Max depth of headings. Default 4

Example:

<!-- AUTO-GENERATED-CONTENT:START (TOC) -->
toc will be generated here
<!-- AUTO-GENERATED-CONTENT:END -->

Default MATCHWORD is AUTO-GENERATED-CONTENT


> CODE

Get code from file or URL and put in markdown

Options:

  • src: The relative path to the code to pull in, or the URL where the raw code lives
  • syntax (optional): Syntax will be inferred by fileType if not specified
  • header (optional): Will add header comment to code snippet. Useful for pointing to relative source directory or adding live doc links
  • 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

Example:

<!-- AUTO-GENERATED-CONTENT:START (CODE:src=./relative/path/to/code.js) -->
This content will be dynamically replaced with code from the file
<!-- AUTO-GENERATED-CONTENT:END -->
 <!-- AUTO-GENERATED-CONTENT:START (CODE:src=./relative/path/to/code.js&lines=22-44) -->
 This content will be dynamically replaced with code from the file lines 22 through 44
 <!-- AUTO-GENERATED-CONTENT:END -->

Default MATCHWORD is AUTO-GENERATED-CONTENT


> FILE

Get local file contents.

Options:

  • src: The relative path to the file to pull in

Example:

<!-- AUTO-GENERATED-CONTENT:START (FILE:src=./path/to/file) -->
This content will be dynamically replaced from the local file
<!-- AUTO-GENERATED-CONTENT:END -->

Default MATCHWORD is AUTO-GENERATED-CONTENT


> REMOTE

Get any remote Data and put in markdown

Options:

  • url: The URL of the remote content to pull in

Example:

<!-- AUTO-GENERATED-CONTENT:START (REMOTE:url=http://url-to-raw-md-file.md) -->
This content will be dynamically replaced from the remote url
<!-- AUTO-GENERATED-CONTENT:END -->

Default MATCHWORD is AUTO-GENERATED-CONTENT


Inline transforms

Any transform, including custom transforms can be used inline as well to insert content into paragraphs and other places.

The face symbol 👉 ⊂◉‿◉つ is auto generated inline.

Example:

<!-- AUTO-GENERATED-CONTENT:START (FILE:src=./path/to/file) -->xyz<!-- AUTO-GENERATED-CONTENT:END -->

🔌 Markdown magic plugins

Adding Custom Transforms

Markdown Magic is extendable via plugins.

Plugins 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.

Plugins run in order of registration.

The below code is used to generate this markdown file via the plugin system.

const fs = require('fs')
const path = require('path')
const doxxx = require('doxxx')
const { markdownMagic } = require('../lib')
// const { markdownMagic } = require('markdown-magic')

const config = {
  matchWord: 'MD-MAGIC-EXAMPLE', // default matchWord is AUTO-GENERATED-CONTENT
  transforms: {
    /* Match <!-- AUTO-GENERATED-CONTENT:START (customTransform:optionOne=hi&optionOne=DUDE) --> */
    customTransform({ content, options }) {
      console.log('original content in comment block', content)
      console.log('options defined on transform', options)
      // options = { optionOne: hi, optionOne: DUDE}
      return `This will replace all the contents of inside the comment ${options.optionOne}`
    },
    /* Match <!-- AUTO-GENERATED-CONTENT:START (RENDERDOCS:path=../file.js) --> */
    RENDERDOCS(api) {
      console.log('api', api)
      const { options } = api
      console.log('options.path', path.resolve(options.path))
      const fileContents = fs.readFileSync(options.path, 'utf8')
      const docBlocs = doxxx.parseComments(fileContents, { raw: true, skipSingleStar: true })
        .filter((item) => {
          return item.tags.length
        })
      console.log('docBlocs', docBlocs)
      // process.exit(1)
      let updatedContent = ''
      docBlocs.forEach((data) => {
        updatedContent += `${data.description.full}\n\n`
      })
      return updatedContent.replace(/^\s+|\s+$/g, '')
    },
    INLINE_EXAMPLE: () => {
      return '**⊂◉‿◉つ**'
    },
    lolz() {
      console.log('run lol')
      return `This section was generated by the cli config markdown.config.js file`
    },
    /* Match <!-- AUTO-GENERATED-CONTENT:START (pluginExample) --> */
    pluginExample: require('./plugin-example')({ addNewLine: true }),
    /* Include plugins from NPM */
    // count: require('markdown-magic-wordcount'),
    // github: require('markdown-magic-github-contributors')
  }
}

const markdownPath = path.join(__dirname, '..', 'README.md')
markdownMagic(markdownPath, config, () => {
  console.log('Docs ready')
})

Plugin Example

Plugins must return a transform function with the following signature.

return function myCustomTransform (content, options)
/* Custom Transform Plugin example */
module.exports = function customPlugin(pluginOptions) {
  // set plugin defaults
  const defaultOptions = {
    addNewLine: false
  }
  const userOptions = pluginOptions || {}
  const pluginConfig = Object.assign(defaultOptions, userOptions)
  // return the transform function
  return function myCustomTransform ({ content, options }) {
    const newLine = (pluginConfig.addNewLine) ? '\n' : ''
    const updatedContent = content + newLine
    return updatedContent
  }
}

View the raw file file and run npm run docs to see this plugin run

This content is altered by the pluginExample plugin registered in examples/generate-readme.js

Other usage examples

Custom Transform Demo

View 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

This will replace all the contents of inside the comment DUDE

Prior Art

This was inspired by Kent C Dodds and jfmengels's all contributors cli project.

License

MIT © DavidWells

Usage examples

Misc Markdown helpers

More Repositories

1

analytics

Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
JavaScript
2,024
star
2

isomorphic-react-example

Deprecated! ReactJS + NodeJS ( express ) demo tutorial with video. Universal/Isomorphic JS = Shared JavaScript that runs on both the client & server.
JavaScript
1,692
star
3

netlify-functions-workshop

Netlify Serverless Functions Workshop
JavaScript
335
star
4

advanced-markdown

Learn about advanced markdown techniques
JavaScript
283
star
5

serverless-workshop

⚡️ Open source serverless workshop. Ready to deploy serverless examples on AWS
JavaScript
184
star
6

responsible

Responsible.js - Give visitors the mobile experience THEY want
JavaScript
164
star
7

serverless-auth-strategies

How to handle authentication with serverless functions
JavaScript
137
star
8

types-with-jsdocs

Using JSDoc for Typescript Types
JavaScript
128
star
9

awesome-stoicism

💆‍♂️ Stoic philosophy resources
JavaScript
124
star
10

safe-await

Safely use async await without all the try/catch blocks
JavaScript
120
star
11

PostCSS-tutorial

Tutorial on adding PostCSS to `create-react-app` CLI
JavaScript
102
star
12

aws-profile-manager

GUI for managing AWS profile credentials.
JavaScript
58
star
13

atom-react-autocomplete

(Deprecated/Maintainer wanted) Atom Plugin for autocompleting react components & their props
JavaScript
55
star
14

next-with-react-router-v6

Next.js with React Router v6 demo
TypeScript
48
star
15

icon-pipeline

🚚 SVG icon pipeline - Optimize icons & build SVG sprites
JavaScript
45
star
16

pnpm-workspaces-example

PNPM workspaces example for monorepos
JavaScript
39
star
17

cache-me-outside

📁 Caching tool for quicker builds in CI systems
JavaScript
37
star
18

react-router-tutorial

Learn how to add routing to your React App
JavaScript
30
star
19

serverless-manifest-plugin

Output manifest of endpoints, resources, outputs, etc. of a serverless service
JavaScript
27
star
20

video-app

👨‍💻 Electron App for showing your webcam in a window thats always on top
JavaScript
26
star
21

react-server-components

Example of react server components running in AWS Lambda deployed via serverless framework
JavaScript
24
star
22

easy-markdown

WordPress Plugin to support Github Flavored Markdown + Syntax Highlighting
PHP
24
star
23

npm-statistics

NPM Download Statistics for David's Open Source Projects
JavaScript
21
star
24

configorama

⚙️ ${variable} support for config files
JavaScript
20
star
25

dom-guard

🔐 Lock DOM node contents to protect people against scammers using browser devtools
HTML
19
star
26

davidwells.io

🌐 David's personal website
JavaScript
17
star
27

middy-example

Serverless project using middy middleware for so fresh & so clean clean lambdas 🛀
JavaScript
14
star
28

markdown-magic-github-contributors

markdown-magic Plugin to list out the contributors of your repository.
JavaScript
13
star
29

react-project-base

Super old. Do not use. My base for starting React Projects
JavaScript
12
star
30

aws-profile-cli

💻 CLI & Utils for managing AWS accounts on your machine
JavaScript
12
star
31

intro-to-react

Introduction to React Core Concepts
JavaScript
12
star
32

netlify-site-as-aws-custom-resource-example

Define Netlify sites as part of an AWS Cloudformation stack.
JavaScript
11
star
33

function-zips

Using zip based functions in Netlify
HTML
11
star
34

use-analytics-with-react-router-demo

Use analytics react hooks with React Router v6
JavaScript
9
star
35

davidwells-legacy-site

👴 David's old personal site
JavaScript
9
star
36

react-example-project

JavaScript
8
star
37

env-stage-loader

Loads .env files in order based on process.env.NODE_ENV value with [stage].local support
JavaScript
8
star
38

oparser

A very forgiving key-value option parser
JavaScript
6
star
39

redux-toolkit-vite-example

TypeScript
6
star
40

netlify-sentry-plugin

WIP - Plugin to automatically run sentry releases
JavaScript
6
star
41

redux-tutorial

JavaScript
6
star
42

debug-plugin-activation-errors

Plugin for Debugging WordPress Plugin Activation Errors. Instead of seeing: "The plugin generated ### characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin." you get the errors being thrown.
PHP
6
star
43

react-autocomplete-cli

CLI companion to the atom-react-autocomplete plugin
JavaScript
4
star
44

happiness-as-a-service

Happiness as a serverless service
JavaScript
4
star
45

js-code-search

Quick links to find how people use npm packages.
JavaScript
4
star
46

scope

🔭 Scope - Create a birdeye's view of your Github project and embed on your site
JavaScript
4
star
47

google-tag-manager-serverless

TODO serverlessify google tag manager serverside implementation
JavaScript
4
star
48

node-docker-workflow

Node Docker Continuous Integration with Express + Redis
Shell
3
star
49

Next-JS-Landing-Page-Starter-Template

next template with tailwind jit & webpack 5
TypeScript
3
star
50

next-with-react-router-v5

Using Next.js as SPA with react router v5
TypeScript
3
star
51

lerna-example

Lerna example for monorepos
JavaScript
3
star
52

repo-using-markdown-magic

Example of repo using markdown magic
JavaScript
3
star
53

analytics-e2e-testing

WIP analytics testing via Cypress
JavaScript
3
star
54

npm-workspaces-example

NPM workspaces example for monorepos
JavaScript
3
star
55

calm

Check if person is calm or not with javascript
JavaScript
3
star
56

explorer-demo-with-video

2
star
57

whats-in-the-cache

Recursively lookup files in a (cache) directory & print a manifest
JavaScript
2
star
58

explorer-demo-weds-two

2
star
59

gitignore-utils

JavaScript
2
star
60

themeable-components-themes

CSS
2
star
61

test-repo-tues-two

HTML
2
star
62

js-library-starter-kit

JavaScript library starter kit for open source projects
JavaScript
2
star
63

parse-npm-script

Parse package.json "script" commands to see how they resolve
JavaScript
2
star
64

explorer-demo-tues-four

2
star
65

simple-supplier-distributor-tues

2
star
66

jsdoc-parser

Updated fork of dox
JavaScript
2
star
67

store-it

Store data in browser. Fallbacks for everythang
JavaScript
2
star
68

mono-repo-example

HTML
2
star
69

WordPress-UI

A CSS Framework and a Set of React Components that Implement WordPress UI
JavaScript
2
star
70

git-er-done

Notice! Moved! See link below...... Utility for dealing with modified, created, deleted files since a git commit.
JavaScript
2
star
71

ryan-wells-foundation

WordPress Site for Ryan Wells Foundation
PHP
1
star
72

my-new-uni

Vendia Universal Application
HTML
1
star
73

next-netlify-blog-starter

JavaScript
1
star
74

react-workshop

1
star
75

safe-chalk

🎨 Terminal colors. Wrapper for chalk package with easy enable/disable option.
JavaScript
1
star
76

react-angular-webpack

React + Angular using ES6 + webpack
JavaScript
1
star
77

vis-tree-demo

JavaScript
1
star
78

customerio-example

JavaScript
1
star
79

electron-dev-setup

Starter project for electron apps
JavaScript
1
star
80

demo-netlify-gated-sites-login-site

JavaScript
1
star
81

redact-logs

Redact sensitive env vars from logs & CLI output.
JavaScript
1
star
82

buslify

Show me da bus
JavaScript
1
star
83

awesomesauce

JavaScript
1
star
84

react-dom-primitives

React Base Dom Primatives
JavaScript
1
star
85

addon-api-example

Example Netlify Add-on API using Netlify functions
JavaScript
1
star
86

netlify-build-mono-repo-base-dir

Mono repo base dir issue https://github.com/homertherefore/netlify-monorepo-project
JavaScript
1
star
87

amplify-vs-cognito-sdk-bundle-size-test

Amplify vs Cognito SDK bundle size test
HTML
1
star
88

minimal-code-sandbox

JavaScript
1
star
89

begin-basic-crud-app

Begin app
HTML
1
star
90

vgs-vanilla-demo

HTML
1
star
91

themeable-components

Themable (at build) react components using CSS
JavaScript
1
star
92

react-router-fibonacci

Fibonacci Sequence with React Router
JavaScript
1
star
93

tiny-cognito

Get AWS Cognito creds to use with aws4fetch
JavaScript
1
star
94

install-github-dep

Git submodules without using submodules
JavaScript
1
star
95

test-repo-cxz

HTML
1
star
96

components

React Components
JavaScript
1
star
97

get-object-diff

JavaScript
1
star
98

react-meetup-demo

Real world react meetup demo!!!!!!!!
JavaScript
1
star
99

react-i18next-advanced

react-i18next with local storage fallback
JavaScript
1
star
100

old-analytics-example

[Old] Example site using `analytics` package
JavaScript
1
star