├── .eslintrc.js ├── .gitignore ├── .npmignore ├── .prettierrc.js ├── LICENSE ├── README.md ├── index.html ├── package-lock.json ├── package.json ├── public └── favicon.ico ├── src ├── components │ └── markvue.vue ├── demo │ ├── App.vue │ ├── content.ts │ ├── main.ts │ └── stubTest.vue ├── env.d.ts ├── index.ts └── utils │ ├── compiler.ts │ ├── nanoid.ts │ └── parser.ts ├── tsconfig.json └── vite.config.ts /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: 'vue-eslint-parser', 3 | parserOptions: { 4 | parser: '@typescript-eslint/parser', 5 | ecmaVersion: 2020, 6 | sourceType: 'module', 7 | }, 8 | extends: ['alloy', 'alloy/typescript', 'alloy/vue', 'plugin:vue/vue3-essential', 'prettier'], 9 | rules: { 10 | 'vue/no-v-model-argument': 0, 11 | 'vue/multi-word-component-names': 0, 12 | }, 13 | }; 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | dist 4 | dist-ssr 5 | *.local 6 | .history 7 | .vscode 8 | lib -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .git 2 | public 3 | index.html 4 | .vscode 5 | .history 6 | .prettierrc.js 7 | tsconfig.json 8 | vite.config.ts 9 | .eslintrc.js 10 | .eslintignore 11 | /src 12 | -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 120, 3 | tabWidth: 2, 4 | semi: true, 5 | singleQuote: true, 6 | trailingComma: 'all', 7 | arrowParens: 'always', 8 | }; 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 BackRunner 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MarkVue 2 | 3 | Allows you to mix Vue component or Vue SFC into Markdown, inspired by `@vue/sfc-playground`. 4 | 5 | ## How to use 6 | 7 | 1: Install the package: 8 | 9 | ```bash 10 | npm install markvue --save 11 | ``` 12 | 13 | 2: Import it to your project: 14 | 15 | ```js 16 | import MarkVue from 'markvue'; 17 | import { createApp } from 'vue'; 18 | import App from './app.vue'; 19 | 20 | const app = createApp(App); 21 | app.use(MarkVue); 22 | 23 | app.mount('#app'); 24 | ``` 25 | 26 | Our component only support Vue 3, Vue 2 is not supported. 27 | 28 | 3: Use it in your pages: 29 | 30 | ```vue 31 | 34 | 35 | 56 | 65 | 66 | 67 | 68 | 73 | 74 | 75 | Here's a vue component stub. 76 | 77 | 78 | ` 79 | export default defineComponent({ 80 | setup() { 81 | return { 82 | content, 83 | }; 84 | }, 85 | }); 86 | 87 | ``` 88 | 89 | For Vue SFC, markvue will inject Vue into the SFC as `context`, you can import APIs from Vue directly. 90 | 91 | If you want to import something from other package, be sure to put it in the `context`, and bind it to markvue, just like this: 92 | 93 | ```vue 94 | 97 | 98 | 114 | 115 | `, 116 | context: { 117 | SOME_PACKAGE: SOMETHING, 118 | }, 119 | }; 120 | 121 | ``` 122 | 123 | You can also put a Vue component into `context` directly, you can mix it into your Markdown like this: 124 | 125 | ```markdown 126 | # Title 127 | 128 | content 129 | 130 | 131 | ``` 132 | 133 | ```vue 134 | 137 | 138 | 147 | ``` 148 | 149 | If you want to add `class` or some other attribute in the root element of Vue SFC or Vue component, you can just add it to the `` or `` tag, like this: 150 | 151 | ```Markdown 152 | 153 | 154 | or 155 | 156 | 157 | 158 | ``` 159 | 160 | For custom options of `marked`, you can set an attribute `markedOptions` to `markvue`, like this: 161 | 162 | ```vue 163 | 166 | ``` 167 | 168 | ## Features 169 | 170 | Supported SFC Features: 171 | 172 | - ` 10 | 11 | 12 |
13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "markvue", 3 | "version": "0.2.4", 4 | "description": "Allows you write Vue SFC directly in Markdown", 5 | "scripts": { 6 | "dev": "vite", 7 | "build": "vue-tsc --noEmit && vite build", 8 | "build:demo": "vue-tsc --noEmit && cross-env BUILD_TARGET=demo vite build", 9 | "serve": "vite preview" 10 | }, 11 | "files": [ 12 | "lib" 13 | ], 14 | "main": "lib/markvue.umd.js", 15 | "module": "lib/markvue.es.js", 16 | "types": "lib/src/index.d.ts", 17 | "homepage": "https://github.com/backrunner/markvue", 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/backrunner/markvue.git" 21 | }, 22 | "sideEffects": false, 23 | "dependencies": { 24 | "@vue/compiler-sfc": "^3.2.31", 25 | "marked": "^4.0.12", 26 | "vue": "^3.2.31" 27 | }, 28 | "devDependencies": { 29 | "@babel/eslint-parser": "^7.17.0", 30 | "@types/lodash-es": "^4.17.6", 31 | "@types/marked": "^4.0.2", 32 | "@types/node": "^16.11.26", 33 | "@typescript-eslint/eslint-plugin": "^5.12.1", 34 | "@typescript-eslint/parser": "^5.12.1", 35 | "@vitejs/plugin-vue": "^2.2.2", 36 | "cross-env": "^7.0.3", 37 | "eslint": "^8.10.0", 38 | "eslint-config-alloy": "^4.5.1", 39 | "eslint-config-prettier": "^8.4.0", 40 | "prettier": "^2.5.1", 41 | "typescript": "^4.5.5", 42 | "vite": "^2.8.4", 43 | "vite-plugin-dts": "^0.9.9", 44 | "vue-eslint-parser": "^8.3.0", 45 | "vue-tsc": "^0.32.0" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/backrunner/markvue/c028a04ce9f8875f394a5aa3357c47b264daffd1/public/favicon.ico -------------------------------------------------------------------------------- /src/components/markvue.vue: -------------------------------------------------------------------------------- 1 | 4 | 5 | 116 | -------------------------------------------------------------------------------- /src/demo/App.vue: -------------------------------------------------------------------------------- 1 | 99 | 100 | 117 | 118 | -------------------------------------------------------------------------------- /src/demo/content.ts: -------------------------------------------------------------------------------- 1 | export const demoContent = ` 2 | # Title 3 | 4 | ## Subtitle 5 | 6 | Here's some content. 7 | 8 | Next is a Vue SFC (counter). 9 | 10 | 11 | 16 | 21 | 32 | 33 | `; 34 | -------------------------------------------------------------------------------- /src/demo/main.ts: -------------------------------------------------------------------------------- 1 | import { createApp } from 'vue'; 2 | import App from './App.vue'; 3 | 4 | createApp(App).mount('#app'); 5 | -------------------------------------------------------------------------------- /src/demo/stubTest.vue: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | -------------------------------------------------------------------------------- /src/env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | declare module '*.vue' { 4 | import { DefineComponent } from 'vue' 5 | // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types 6 | const component: DefineComponent<{}, {}, any> 7 | export default component 8 | } 9 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { App } from 'vue'; 2 | import MarkVue from './components/markvue.vue'; 3 | 4 | const installer = (app: App) => { 5 | app.component(MarkVue.name, MarkVue); 6 | }; 7 | 8 | export default installer; 9 | -------------------------------------------------------------------------------- /src/utils/compiler.ts: -------------------------------------------------------------------------------- 1 | import { compileScript, compileStyle, compileTemplate, parse, SFCTemplateCompileOptions } from '@vue/compiler-sfc'; 2 | 3 | const isProd = process.env.NODE_ENV === 'production'; 4 | 5 | export const createVueSFCModule = async (id: string, source: string) => { 6 | const component: { [key: string]: any } = {}; 7 | const { descriptor, errors } = parse(source); 8 | 9 | const templateOptions: SFCTemplateCompileOptions = { 10 | filename: id, 11 | source: descriptor.template?.content || '', 12 | isProd, 13 | id, 14 | slotted: descriptor.slotted, 15 | scoped: descriptor.styles.some((style) => style.scoped), 16 | ssr: false, 17 | compilerOptions: { 18 | mode: 'module', 19 | }, 20 | }; 21 | 22 | if (descriptor.script || descriptor.scriptSetup) { 23 | const scriptBlock = compileScript(descriptor, { 24 | isProd, 25 | id, 26 | inlineTemplate: false, 27 | templateOptions: templateOptions, 28 | }); 29 | templateOptions.compilerOptions!.bindingMetadata = scriptBlock.bindings; 30 | component.script = scriptBlock.content; 31 | } else { 32 | component.script = ''; 33 | } 34 | 35 | if (descriptor.template) { 36 | component.template = compileTemplate(templateOptions).code; 37 | } else { 38 | component.template = ''; 39 | } 40 | 41 | if (descriptor.styles) { 42 | const styleContents = await Promise.all( 43 | descriptor.styles.map((style, index) => { 44 | const filename = `${id}_styles_${index}`; 45 | return compileStyle({ 46 | filename, 47 | id, 48 | scoped: style.scoped, 49 | source: style.content, 50 | trim: true, 51 | isProd, 52 | }).code; 53 | }), 54 | ); 55 | component.styles = styleContents.join('\n'); 56 | } else { 57 | component.styles = ''; 58 | } 59 | 60 | component.id = id; 61 | component.type = 'sfc'; 62 | 63 | return component; 64 | }; 65 | -------------------------------------------------------------------------------- /src/utils/nanoid.ts: -------------------------------------------------------------------------------- 1 | import { customAlphabet } from 'nanoid'; 2 | 3 | export const nanoid = customAlphabet('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 10); 4 | -------------------------------------------------------------------------------- /src/utils/parser.ts: -------------------------------------------------------------------------------- 1 | import { nanoid } from './nanoid'; 2 | import { marked } from 'marked'; 3 | import { createVueSFCModule } from './compiler'; 4 | 5 | interface ParsedComponent { 6 | template?: string; 7 | styles?: string; 8 | script?: string; 9 | name?: string; 10 | type: 'sfc' | 'comp'; 11 | } 12 | 13 | export interface ParsedComponentWithId extends ParsedComponent { 14 | id: string; 15 | } 16 | 17 | export interface ParseOptions { 18 | marked?: marked.MarkedOptions; 19 | } 20 | 21 | const VUE_SFC_REGEX = /[\r?\n]+([\S\s]+?)[\r?\n]+<\/vue-sfc>/gim; 22 | const VUE_COMP_REGEX = /(\s*<\/vue-comp>)?/gim; 23 | const COMPONENT_REGEX = /\s*component=["'](\S+)["']/; 24 | 25 | const getVueSFCTemplates = (content: string) => { 26 | let transformedContent = content; 27 | const sfcTemplates = [...content.matchAll(VUE_SFC_REGEX)].map((parts) => { 28 | const sfcId = nanoid(); 29 | transformedContent = transformedContent.replace(parts[0], `
`); 30 | return { 31 | id: sfcId, 32 | sfc: parts[2], 33 | }; 34 | }); 35 | return { 36 | transformedContent, 37 | templates: sfcTemplates, 38 | }; 39 | }; 40 | 41 | const getVueCompDetails = (content: string) => { 42 | let transformedContent = content; 43 | const stubComponents: ParsedComponentWithId[] = [...content.matchAll(VUE_COMP_REGEX)] 44 | .map((parts) => { 45 | console.log(parts); 46 | const compId = nanoid(); 47 | const attrs = parts[1]; 48 | if (!attrs) { 49 | console.error('[MarkVue] Cannot find any attributes in .'); 50 | return null; 51 | } 52 | const nameMatch = parts[1].match(COMPONENT_REGEX); 53 | if (!nameMatch || !nameMatch[1]) { 54 | console.error('[MarkVue] Cannot find attribute "component" in .'); 55 | return null; 56 | } 57 | const name = nameMatch[1]; 58 | const componentRemovedAttrs = parts[1].replace(nameMatch[0], ''); 59 | transformedContent = transformedContent.replace( 60 | parts[0], 61 | `
`, 62 | ); 63 | return { 64 | id: compId, 65 | type: 'comp', 66 | name, 67 | }; 68 | }) 69 | .filter((item) => !!item) as ParsedComponentWithId[]; 70 | return { 71 | stubTransformedContent: transformedContent, 72 | stubComponents, 73 | }; 74 | }; 75 | 76 | const IMPORT_REGEX = /import\s+(.+)\s+from\s*["'](.+)["'];?/gi; 77 | 78 | const transformImports = (script: string) => { 79 | const importMatches = [...script.matchAll(IMPORT_REGEX)].map((item) => { 80 | let namedImport = false; 81 | return { 82 | matched: item[0], 83 | imported: item[1] 84 | .split(',') 85 | .map((part: string) => { 86 | if (part.includes('{')) { 87 | namedImport = true; 88 | } 89 | const formatted = part.replace('{', '').replace('}', '').trim(); 90 | const ret = namedImport ? `{ ${formatted} }` : formatted; 91 | if (part.includes('}')) { 92 | namedImport = false; 93 | } 94 | return ret; 95 | }) 96 | .map((importedComponent: string) => { 97 | let formatted = importedComponent.trim(); 98 | if (formatted.startsWith('{')) { 99 | formatted = formatted.replace('{', '').replace('}', '').trim(); 100 | if (formatted.includes('as')) { 101 | const containAlias = formatted.split('as').map((part) => part.trim()); 102 | return containAlias; 103 | } 104 | return `{ ${formatted} }`; 105 | } else { 106 | return formatted; 107 | } 108 | }), 109 | from: item[2], 110 | }; 111 | }); 112 | let ret = script; 113 | importMatches.forEach((match) => { 114 | const transformed = match.imported.map((imported) => { 115 | if (Array.isArray(imported)) { 116 | return `const ${imported[1] || imported[0]} = context['${match.from}']['${imported[0]}']`; 117 | } 118 | return `const ${imported} = context['${match.from}']`; 119 | }); 120 | ret = ret.replace(match.matched, transformed.join('\n')); 121 | }); 122 | return ret; 123 | }; 124 | 125 | const transformScriptCode = (id: string, script: string) => { 126 | const importTransformed = transformImports(script).trim(); 127 | if (importTransformed) { 128 | return `(function() { window.markVueModules['${id}'].getScript = function (context) {\n${importTransformed.replace( 129 | 'export default', 130 | 'return', 131 | )}\n}; })()`; 132 | } 133 | return ''; 134 | }; 135 | 136 | const transformTemplateCode = (id: string, script: string) => { 137 | const importTransformed = transformImports(script).trim(); 138 | if (importTransformed) { 139 | return `(function() { window.markVueModules['${id}'].getTemplate = function (context) {\n${importTransformed.replace( 140 | 'export', 141 | 'return', 142 | )}\n} })()`; 143 | } 144 | return ''; 145 | }; 146 | 147 | export const parse = async (content: string, options?: ParseOptions) => { 148 | const { transformedContent, templates } = getVueSFCTemplates(content); 149 | const components = await Promise.all( 150 | templates.map( 151 | async (item) => 152 | ({ 153 | id: item.id, 154 | ...((await createVueSFCModule(item.id, item.sfc)) as ParsedComponent), 155 | } as ParsedComponentWithId), 156 | ), 157 | ); 158 | // wrap compiled script 159 | const wrappedComponents: ParsedComponentWithId[] = components.map((item) => ({ 160 | ...item, 161 | script: transformScriptCode(item.id, item.script!), 162 | template: transformTemplateCode(item.id, item.template!), 163 | })); 164 | // get stub component 165 | const { stubTransformedContent, stubComponents } = getVueCompDetails(transformedContent); 166 | return { 167 | parsedContent: marked(stubTransformedContent, options?.marked || undefined), 168 | components: wrappedComponents.concat(stubComponents), 169 | }; 170 | }; 171 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "esnext", 4 | "useDefineForClassFields": true, 5 | "module": "esnext", 6 | "moduleResolution": "node", 7 | "strict": true, 8 | "jsx": "preserve", 9 | "sourceMap": true, 10 | "resolveJsonModule": true, 11 | "esModuleInterop": true, 12 | "lib": ["esnext", "dom"] 13 | }, 14 | "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"] 15 | } 16 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import path from 'path'; 3 | import vue from '@vitejs/plugin-vue'; 4 | import dts from 'vite-plugin-dts'; 5 | 6 | const BuildConfig = { 7 | lib: { 8 | plugins: [vue(), dts()], 9 | build: { 10 | sourcemap: true, 11 | minify: 'terser' as 'terser', 12 | outDir: 'lib', 13 | lib: { 14 | entry: path.resolve(__dirname, './src/index.ts'), 15 | name: 'markvue', 16 | formats: ['es', 'umd'], 17 | }, 18 | rollupOptions: { 19 | external: ['vue', 'marked', '@vue/compiler-sfc'], 20 | output: { 21 | globals: { 22 | vue: 'Vue', 23 | marked: 'Marked', 24 | '@vue/compiler-sfc': 'compilerSfc', 25 | }, 26 | }, 27 | }, 28 | }, 29 | }, 30 | demo: { 31 | plugins: [vue()], 32 | build: { 33 | sourcemap: true, 34 | minify: 'terser' as 'terser', 35 | outDir: 'dist', 36 | }, 37 | }, 38 | }; 39 | 40 | // https://vitejs.dev/config/ 41 | export default defineConfig(process.env.BUILD_TARGET === 'demo' ? BuildConfig.demo : BuildConfig.lib); 42 | --------------------------------------------------------------------------------