Giter Site home page Giter Site logo

hmsk / vite-plugin-markdown Goto Github PK

View Code? Open in Web Editor NEW
245.0 3.0 43.0 1.71 MB

A vite plugin to import a Markdown file in various formats like Front Matter, HTML, ToC, and React/Vue Component

Home Page: https://www.npmjs.com/package/vite-plugin-markdown

License: MIT License

TypeScript 71.69% JavaScript 28.31%
vite frontmatter markdown markdown-it vue react

vite-plugin-markdown's Introduction

vite-plugin-markdown

npm npm beta channel

A plugin enables you to import a Markdown file as various formats on your vite project.

Setup

npm i -D vite-plugin-markdown
For vite v1
npm i -D vite-plugin-markdown@vite-1

Config

const mdPlugin = require('vite-plugin-markdown')

module.exports = {
  plugins: [mdPlugin(options)]
}

Then you can import front matter attributes from .md file as default.

---
title: Awesome Title
description: Describe this awesome content
tags:
  - "great"
  - "awesome"
  - "rad"
---

# This is awesome

Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.
import { attributes } from './contents/the-doc.md';

console.log(attributes) //=> { title: 'Awesome Title', description: 'Describe this awesome content', tags: ['great', 'awesome', 'rad'] }

Options

mode?: ('html' | 'markdown' | 'toc' | 'react' | 'vue')[]
markdown?: (body: string) => string
markdownIt?: MarkdownIt | MarkdownIt.Options

Enum for mode is provided as Mode

import { Mode } from 'vite-plugin-markdown'

console.log(Mode.HTML) //=> 'html'
console.log(Mode.MARKDOWN) //=> 'markdown'
console.log(Mode.TOC) //=> 'toc'
console.log(Mode.REACT) //=> 'react'
console.log(Mode.VUE) //=> 'vue'

"Mode" enables you to import markdown file in various formats (HTML, ToC, React/Vue Component)

Mode.HTML

Import compiled HTML
# This is awesome

Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.
import { html } from './contents/the-doc.md';

console.log(html) //=> "<h1>This is awesome</h1><p>ite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.</p>"

Mode.MARKDOWN

Import the raw Markdown content
import { markdown } from './contents/the-doc.md'

console.log(markdown) //=> "# This is awesome \n Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production."

Mode.TOC

Import ToC metadata
# vite

Vite is an opinionated web dev build tool that serves your code via native ES Module imports during dev and bundles it with Rollup for production.

## Status

## Getting Started

# Notes
import { toc } from './contents/the-doc.md'

console.log(toc) //=> [{ level: '1', content: 'vite' }, { level: '2', content: 'Status' }, { level: '2', content: 'Getting Started' }, { level: '1', content: 'Notes' },]

Mode.REACT

Import as a React component
import React from 'react'
import { ReactComponent } from './contents/the-doc.md'

function MyReactApp() {
  return (
    <div>
      <ReactComponent />
    </div>
}
Custom Element on a markdown file can be runnable as a React component as well
# This is awesome

Vite is <MyComponent type={'react'}>
import React from 'react'
import { ReactComponent } from './contents/the-doc.md'
import { MyComponent } from './my-component'

function MyReactApp() {
  return (
    <div>
      <ReactComponent MyComponent={MyComponent} />
    </div>
}

MyComponent on markdown perform as a React component.

Mode.VUE

Import as a Vue component
<template>
  <article>
    <markdown-content />
  </article>
</template>

<script>
import { VueComponent } from './contents/the-doc.md'

export default {
  components: {
    MarkdownContent: VueComponent
  }
};
</script>
Custom Element on a markdown file can be runnable as a Vue component as well
# This is awesome

Vite is <MyComponent :type="'vue'">
<template>
  <article>
    <markdown-content />
  </article>
</template>

<script>
import { VueComponentWith } from './contents/the-doc.md'
import MyComponent from './my-component.vue'

export default {
  components: {
    MarkdownContent: VueComponentWith({ MyComponent })
  }
};
</script>

MyComponent on markdown perform as a Vue component.

Type declarations

In TypeScript project, need to declare typedefs for .md file as you need.

declare module '*.md' {
  // "unknown" would be more detailed depends on how you structure frontmatter
  const attributes: Record<string, unknown>; 

  // When "Mode.TOC" is requested
  const toc: { level: string, content: string }[];

  // When "Mode.HTML" is requested
  const html: string;

  // When "Mode.RAW" is requested
  const raw: string

  // When "Mode.React" is requested. VFC could take a generic like React.VFC<{ MyComponent: TypeOfMyComponent }>
  import React from 'react'
  const ReactComponent: React.VFC;
  
  // When "Mode.Vue" is requested
  import { ComponentOptions, Component } from 'vue';
  const VueComponent: ComponentOptions;
  const VueComponentWith: (components: Record<string, Component>) => ComponentOptions;

  // Modify below per your usage
  export { attributes, toc, html, ReactComponent, VueComponent, VueComponentWith };
}

Save as vite.d.ts for instance.

License

MIT

vite-plugin-markdown's People

Contributors

carrettariccardo avatar dafrok avatar danawoodman avatar dependabot[bot] avatar deviltea avatar ferm10n avatar hmsk avatar sapphi-red avatar stefanvanherwijnen avatar zhengzhibo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

vite-plugin-markdown's Issues

npm i vite-plugin-markdown error

sudo npm i vite-plugin-markdown

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR!   dev vite@"^4.3.9" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer vite@"^2.0.0 || ^3.0.0" from [email protected]
npm ERR! node_modules/vite-plugin-markdown
npm ERR!   vite-plugin-markdown@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! /Applications/MxSrvs/cache/nodejs/_logs/2023-06-30T08_33_15_545Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in:
npm ERR!     /Applications/MxSrvs/cache/nodejs/_logs/2023-06-30T08_33_15_545Z-debug-0.log

No html mode

I am using your plugin with Quasar framework. Here is my simple page.

<template>
    <q-page class="flex flex-center">
        <div class="q-pa-lg">
            {{ html }}
        </div>
    </q-page>
</template>

<script>
import { defineComponent } from 'vue'
import { attributes, html } from '../statics/lib/gost/gost.50571.7.702-2013.md';

export default defineComponent({
    name: 'IndexPage',
    setup() {
        console.log(attributes, html);
        return {
            html
        }
    }
})
</script>

I do get attributes but if I add html I have this error

SyntaxError: The requested module '/src/statics/lib/gost/gost.50571.7.702-2013.md?import' does not provide an export named 'html'

What do I miss?

display local image file

So far most of the Markdown implementation is using absolute url such as http://www.url.com/imagefile.jpg.

I wonder if we can use local file for displaying the image using relative url.

For example :

folder
-- image.png
-- index.md

in index.md :

![yay image](./image.png)

ReferenceError: vueRender is not defined

Vue: 2.6.x
Vite: 4.x
vite-plugin-markdown: 2.1.0

import { VueComponent } from './pages/00-intro.md'

···

components: {
    MarkdownContent: VueComponent
}

···

<MarkdownContent/>

image

error: failed to resolve soc

Here it's the thing: I want to use it in vue with toc, but vite failed to resolve toc component and there's no href on h* tags. can't figure out how to solve it, can you provide a guide?

add ESM support to the build

It'd be great to see ESM module support added now that it's stable in node 15.

This plugin has been super convenient on a site I'm testing SvelteKit with. They just recently switched the config file format for SvelteKit projects from commonjs to esm, I'm assuming ViteKit and others will start moving that way now that node supports it.

`Mode.MARKDOWN` does not exist on type `Mode`

Version: 2.1.0

The documentation states:

Enum for mode is provided as Mode

import { Mode } from 'vite-plugin-markdown'

console.log(Mode.HTML) //=> 'html'
console.log(Mode.MARKDOWN) //=> 'markdown'

However, Mode.MARKDOWN is not defined. (All other documented modes are, however).

import { defineConfig } from 'vite'
import { plugin as mdPlugin, Mode } from 'vite-plugin-markdown'

export default defineConfig({
  plugins: [
    vue(),
    mdPlugin({
      mode: [Mode.MARKDOWN], // error: Property 'MARKDOWN' does not exist on type 'typeof Mode'
    }),
  ],

Consequently, I cannot import markdown as markdown in my JS.

import { markdown as readme } from './README.md'

./README.md does not provide an export named 'markdown'

Sourcemap issues

Getting this error when enabling sourcemaps (vite-plugin-import-markdown plugin) Sourcemap is likely to be incorrect: a plugin (vite-plugin-import-markdown) was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help

use esbuild instead of babel to transform jsx syntax

I am using react and need to display some markdown file.
And when I install vite-plugin-markdown then run dev server, it thorwed an error 'module @babel/preset-react not found' so I have to install it manually.
I just read vite's code about transfroming jsx syntax.It uses esbuild.
I think it is not neccessary to use babel because vite uses esbuild internally.

Need to support Vite 4

Sveltekit is moving to be based on Vite 4. It seems that vite-plugin-markdown now needs to vite 2, 3 & 4 as possible dependencies

`compileTemplate` function needs new `id` argument

Using this package with compiler-sfc 3.0.4 shows the following message:

[@vue/compiler-sfc] compileTemplate now requires the `id` option.`.

Should be an easy fix, just I thought I'd point it out. The plugin still seems to be working, I thiiink...? Not completely sure.

Can I use it without react or vue?

Can I use it without react or vue? I just want to use it in a simple application with vite and html + js + css.
I have tried it, but got error:

image

vite.config.js is:

import { defineConfig } from 'vite';
import path from "path";
import mdPlugin, { Mode }  from "vite-plugin-markdown"

const { resolve } = path;

export default defineConfig({
  server: {
    port: 2023,
    host: "0.0.0.0",
  },
  resolve: {
  alias: [
    { find: "@", replacement: resolve(__dirname, "./src") },
  ],
  },
  plugins: [
    mdPlugin.plugin({ mode: [Mode.HTML, Mode.MARKDOWN, Mode.TOC] })
  ],
})

mypage.tsx:

import Hello, { attributes } from "./defining.md"

console.log(Hello, attributes, 11);

Example with react doesn't work

This doesn't work. But it works ok if I name props that way <ReactComponent MyComponent={MyComponent} />.

import React from 'react'
import { ReactComponent } from './contents/the-doc.md'
import { MyComponent } from './my-component'

function MyReactApp() {
  return (
    <div>
      <ReactComponent my-component={MyComponent} />
    </div>
}

npm ERR! ERESOLVE unable to resolve dependency tree (Svelte 3.44.0)

First: thank you so much for making this library! It seems like it will fill my exact current need. However, I am having trouble installing it...

This issue popped up before (#324) but seems to be a problem again.

When I try to install, I receive the following error:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR!   dev vite@"^3.1.0-beta.1" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer vite@"^2.0.0 || ^3.0.0" from [email protected]
npm ERR! node_modules/vite-plugin-markdown
npm ERR!   dev vite-plugin-markdown@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/stephennixon/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/stephennixon/.npm/_logs/2022-09-03T20_29_59_223Z-debug-0.log

Is there a suggested workaround for this?

Allow passing more options to VueComponentWith()

It would be nice to allow other Vue Component options then components when using Vue syntax in .md file. For example props can be useful as well. There could be a second function parameter called options, like so: VueComponentWith(components, options)

import { VueComponentWith } from '../contents/test.md';

const TestComponent = VueComponentWith({ ... }, {
   props: ['prop1', ...]
});

Is anyway or plan to add script to md ?

content.md

<link-to-repository color="#37ae70">See Repository</link-to-repository>

change to

<link-to-repository :color="color">See Repository</link-to-repository>

<script>
export default {
  data() {
    return {
      color: "#37ae70",
    };
  },
};
</script>

and add style tag , just like vuepress

Unsupported for html comments ?

i was commented the markdown like

image

got error

image

[plugin:vite-plugin-markdown] unknown: Unexpected token (28:1)
  31 | <h2>Download</h2>

E:/Repositories/android-blog/release-repo/readme.md:28:1

28 |  <!-- |      |        |      |
29 |  | :--- | :----: | ---: |
30 |  | ![Homepage](./images/Screenshot_2023-10-26-08-56-48-99_7f9c0e40e1157fc4be382fed75dcb9a6.jpg "Homepage") | ![Point Earning](./images/Screenshot_2023-10-26-08-56-58-82_7f9c0e40e1157fc4be382fed75dcb9a6.jpg "Point Earning") | ![Local Exchanger](./images/Screenshot_2023-10-26-08-57-06-96_7f9c0e40e1157fc4be382fed75dcb9a6.jpg "Local Exchanger") | -->
   |                                                                                                                                                                           ^
31 |  
32 |  ## Download

Uncaught TypeError: ssrContext is undefined

I'm sorry Im Noob, i found error at the browser console, it said Uncaught TypeError: ssrContext is undefined, i don't know what to do, should i add SSR to my existing app?

Error : cannot find module or its corresponding type declarations.

Hi everyone,

Great plug-in, everything works fine on the local server. Unfortunately when I try to build the app, I get the following errors:

Cannot find module '../content/blog/2022-test/text.md' or its corresponding type declarations. ts(2307)
Cannot find module '../content/blog/2022-test/text2.md' or its corresponding type declarations. ts(2307)
Cannot find module '../content/blog/2022-test/text3.md' or its corresponding type declarations. ts(2307)

When trying to import files like that :

import * as Article1 from "../content/blog/2022-test/text.md"
import * as Article2 from "../content/blog/2022-test2/text.md"
import * as Article3 from "../content/blog/2022-test3/text.md"

export const blogArticles = [
  Article1,
  Article2,
  Article3,
]

content/blog/2022-test/text.md looks like :

---
url: "2022-test"
title: "test"
date: "2022-03-01"
authors:
  - 'Goulven "Nev" CLEC''H'
color: "green"
cover: "cover.png"
---

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. 

src/vite-env.d.ts looks like :

/// <reference types="vite/client" />
import { Colors } from "./Type"
import React from "react"

// Needed by vite-plugin-markdown
declare module "*.md" {
  const attributes: {
    url: string
    title: string
    date: Date
    authors: Array<string>
    color: Colors
    cover: string
  }

  // When "Mode.TOC" is requested
  const toc: { level: string; content: string }[]

  // When "Mode.HTML" is requested
  const html: string

  // When "Mode.React" is requested. VFC could take a generic like React.VFC<{ MyComponent: TypeOfMyComponent }>
  const ReactComponent: React.VFC

  // Modify below per your usage
  export { attributes, toc, html, ReactComponent }
}

Vite's config looks like :

import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"
import mdPlugin, { Mode } from "vite-plugin-markdown"
import markdownItFootnote from "markdown-it-footnote"
import markdownIt from "markdown-it"

// https://vitejs.dev/config/
export default defineConfig({
  publicDir: "content",
  plugins: [
    react(),
    mdPlugin({
      mode: [Mode.TOC, Mode.HTML, Mode.REACT],
      markdownIt: markdownIt({ html: true }).use(markdownItFootnote),
    }),
  ],

Versions :

  "dependencies": {
    "react": "^17.0.2",
    [...]
  },
  "devDependencies": {
    [...]
    "typescript": "^4.4.4",
    "vite": "^2.7.2",
    "vite-plugin-markdown": "^2.0.2"
  }

Thanks for your help 😃

Support for Vite 5

Hi there!

Just wanted to check if this plugin supports vite 5? I currently get a peer dependency issue when installing

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR!   dev vite@"^5.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer vite@"^2.0.0 || ^3.0.0" from [email protected]
npm ERR! node_modules/vite-plugin-markdown
npm ERR!   dev vite-plugin-markdown@"^2.1.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! 
npm ERR! For a full report see:
npm ERR! /Users/branclon/.npm/_logs/2023-11-18T06_03_46_093Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/branclon/.npm/_logs/2023-11-18T06_03_46_093Z-debug-0.log

@babel/preset-react should be in package.json dependencies

 | [vite-plugin-markdown] Cannot find module '@babel/preset-react'
 | Require stack:
 | - /my-repo/node_modules/@babel/core/lib/config/files/plugins.js
 | - /my-repo/node_modules/@babel/core/lib/config/files/index.js
 | - /my-repo/node_modules/@babel/core/lib/index.js
 | - /my-repo/node_modules/@prefresh/vite/src/index.js
 | - /my-repo/node_modules/@preact/preset-vite/dist/cjs/index.js
 | - /my-repo/packages/apps/my-app/config/vite.config.ts
 | - /my-repo/node_modules/vite/dist/node/chunks/dep-a8e37fae.js
 | file: /my-repo/packages/apps/my-app/src/assets/my-file.md

Add plain string mode support

Type

Feature Request

Feature

What about just having a plain string text to import markdown files in Vite? I would like to process the markdown file in a different way than the HTML mode is providing right now.


Thank you!

The plugin needs export "default" in Vue mode

  • vite: v2.0.0-beta.31
  • vue: v3.0.5

When i use this plugin, the console will show The requested module '/src/markdown.md?import' does not provide an export named 'default'.

Here is my code:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

import { plugin as markdown, Mode } from 'vite-plugin-markdown'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import taskList from 'markdown-it-task-lists'

const markdownIt: MarkdownIt.Options = new MarkdownIt({
  html: true,
  highlight: function (str: string, lang: string) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(lang, str).value
    }
    return ''
  }
}).use(taskList)

export default defineConfig({
  plugins: [vue(), markdown({ mode: [Mode.VUE], markdownIt })]
})

If export default VueComponent;, and it works.

use vite3+vue3,not support require('vite-plugin-markdown')

vite.config.ts is:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const mdPlugin = require('vite-plugin-markdown') // 需要通过commenJs方式引用

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    mdPlugin.plugin({
      mode: ['html'],
    })
  ],
  base: './'
})

but npm run dev get error - Dynamic require of "vite-plugin-markdown" is not supported:

failed to load config from /Users/wushao/wushaoDev/FE-stuty/vue3-demo/vite.config.ts
error when starting dev server:
Error: Dynamic require of "vite-plugin-markdown" is not supported
    at file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/vite.config.ts.timestamp-1663848973291.mjs:6:9
    at file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/vite.config.ts.timestamp-1663848973291.mjs:12:16
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:533:24)
    at async loadConfigFromBundledFile (file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/node_modules/vite/dist/node/chunks/dep-557f29e6.js:63494:21)
    at async loadConfigFromFile (file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/node_modules/vite/dist/node/chunks/dep-557f29e6.js:63380:28)
    at async resolveConfig (file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/node_modules/vite/dist/node/chunks/dep-557f29e6.js:62997:28)
    at async createServer (file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/node_modules/vite/dist/node/chunks/dep-557f29e6.js:62063:20)
    at async CAC.<anonymous> (file:///Users/wushao/wushaoDev/FE-stuty/vue3-demo/node_modules/vite/dist/node/cli.js:700:24)

异常:TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:3:28)

异常:TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (:3:28)

ChatGPT
这个错误提示通常与在严格模式(strict mode)下访问非法属性有关。在严格模式下,不允许访问一些不安全的属性,如 'caller'、'callee' 和 'arguments'。这些属性在函数内部可能导致一些安全问题,因此在严格模式下被禁止使用。

从你提供的错误提示中来看,这个错误似乎是在一个匿名函数中发生的。具体地,它涉及到了一个叫做 invokeGetter 的函数。

要解决这个问题,你可以考虑以下几个步骤:

定位问题代码:

首先,要找出哪一部分的代码触发了这个错误。错误信息中可能会提供堆栈跟踪,指出问题发生的文件和行号。你可以根据堆栈跟踪来定位问题代码。

检查是否在严格模式下:

确保你的代码没有在严格模式下使用 'caller'、'callee' 或 'arguments' 属性。严格模式可以通过在代码文件的顶部添加 "use strict"; 来启用,如果你不需要严格模式,可以尝试移除这个声明。

避免直接使用 'arguments':

'arguments' 对象在箭头函数中是不可用的,而在函数内部也尽量避免使用。如果你正在使用箭头函数,确保不直接使用 'arguments'。而在普通函数中,也建议使用具名参数或 rest 参数,而不是直接使用 'arguments'。

检查依赖库版本:
这个问题可能与某些依赖库的版本不兼容有关。确保你的依赖库版本是最新的,并查看依赖库的文档是否提到了这个问题。
如果你能够提供更多代码上下文,我可能能够提供更准确的帮助。如果问题仍然存在,我建议在社区中寻求更详细的帮助,或者在相关库的 GitHub 存储库中提问

how to use img in MD

it is not work when you use

[RUNOOB 图标](http://static.runoob.com/images/runoob-logo.png) 
 <img src="http://static.runoob.com/images/runoob-logo.png" width="50%"> 

in MD. the problem is show in blow:

16:27:51 [vite] Internal server error: unknown: Unterminated JSX contents (19:14)

  17 | <img src="http://static.runoob.com/images/runoob-logo.png" width="375">
  18 |
> 19 |         </div>
     |               ^
  20 |     
  Plugin: vite-plugin-markdown

Dynamically loading markdown files

is it possible to use these function as if I were loading it from a variable instead of a specified path?

e.g.

// This
export let mdFile;

import { toc, html, attributes } from mdFile;

// Over This
import { toc, html, attributes } from '$lib/markdown/test.md';

Integrate into another backend template

Hi there,

I am trying to integrate this amazing plugin into the vue-vben-admin template. However, there is no clue about how to properly configure the project as the vite config is complicated there. Would you please give me some hint?

Thank you

add missing docs for typescript ESM

here my working config vite.config.ts

import react from '@vitejs/plugin-react';
import dotenv from 'dotenv';
import { createRequire } from 'node:module';
import path from 'upath';
import { UserConfig, defineConfig } from 'vite';
import * as mdp from 'vite-plugin-markdown';

const { plugin: mdPlugin, Mode } = mdp;
dotenv.config({ override: true });

const require = createRequire(import.meta.url);

const config: UserConfig = {
  plugins: [react(), mdPlugin({ mode: [Mode.HTML, Mode.MARKDOWN, Mode.TOC, Mode.REACT] })],
  server: {
    port: 4000
  },
  resolve: {
    alias: {
      '*': path.resolve('.'),
      '@utils': path.resolve('./src/utils'),
      '@components': path.resolve('./src/components'),
      '@routes': path.resolve('./src/routes'),
      '@assets': path.resolve('./src/assets'),
      '@src': path.resolve('./src'),
      '@root': path.resolve('./'),
      '@post': path.resolve('./src/posts'),
      'react/jsx-dev-runtime': require.resolve('react/jsx-dev-runtime'),
      'react/jsx-runtime': require.resolve('react/jsx-runtime')
    }
  }
};

export default defineConfig(config);

package.json

{ "type": "module" }

Cannot use Vue component inside Markdown

Hello, I'm trying to use Vue components inside Markdown following your example in the README but I keep getting this error in the console:

[Vue warn]: Failed to resolve component: helloworld
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement. 
  at <Anonymous> 
  at <App>

Here are the relevant files from a newly created Vite Vue app:

vite.config.js

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import mdPlugin from "vite-plugin-markdown";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [mdPlugin({ mode: "vue" }), vue()],
});

App.vue

<script setup>
import { VueComponentWith } from "./test.md";
import HelloWorld from "./components/HelloWorld.vue";
const WithHello = VueComponentWith({ HelloWorld });
</script>

<template>
  <article>
    <WithHello />
  </article>
</template>

test.md

---
title: Test
date: 2022-07-07
---

# This is a test

* Uno
* Dos
* Tres

> A blockquote

<HelloWorld msg="Hello Vue 3 + Vite" />

Here is a link to the repo containing the code above: https://github.com/lobo-tuerto/markdown-vue

Maybe I'm missing something super obvious... help. :|

there is no type : Mode.RAW

image

version:
vite-plugin-markdown: "^2.1.0",

I would like to load markdown files in a string/raw format.

i had check the README , but i cant find the solution
What should I do?

Can you please update to Vite 3?

I can't update my project's main dependency SvelteKit to the latest version as it depends on Vite 3, and since vite-plugin-markdown depends on Vite 2, that gives a conflict.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: [projectname]@0.0.1
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR!   peer vite@"^3.0.0" from @sveltejs/[email protected]
npm ERR!   node_modules/@sveltejs/kit
npm ERR!     dev @sveltejs/kit@"next" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! dev vite-plugin-markdown@"^2.0.2" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/vite
npm ERR!   peer vite@"^2.0.0" from [email protected]
npm ERR!   node_modules/vite-plugin-markdown
npm ERR!     dev vite-plugin-markdown@"^2.0.2" from the root project

[FR] Additional output modes

Would it be possible to add additional modes to the plugin like raw and text? Raw would would just return the raw markdown and text would return a string where all the MD syntax is stripped from the file. This would be a nice-to-have.

*.md declaration files for typescript

I had to make a .d.ts file for the *.md files that I have used. So far it looks something like this:

import { ReactNode } from "react";

declare module "*.md" {
    export type TableOfContents = {
        level: string;
        content: string;
    }[];

    const res: {
        html?: string;
        ReactComponent: ReactNode;
        attributes: Record<string, never>;
        toc: TableOfContents;
    };
    export default res;
}

I can make a PR for this so that markdown files can be imported in tsx components without problems.

Does not work for storybook

I am trying to use markdown plugin in storybook but I got error message saying ReactComponent is exported from markdownfile.md. Did I do something wrong? The SVG plugin is working

const { Mode, plugin: mdPlugin } = require('vite-plugin-markdown');

const svgrPlugin = require('vite-plugin-svgr');

module.exports = {
  stories: ['../src/stories/**/*.stories.mdx', '../src/stories/**/*.stories.@(js|jsx|ts|tsx)'],
  addons: ['@storybook/addon-links', '@storybook/addon-essentials', '@storybook/addon-a11y'],
  framework: '@storybook/react',
  core: {
    builder: 'storybook-builder-vite',
  },
  features: {
    storyStoreV7: true,
  },
  async viteFinal(config, { configType }) {
    config.plugins.push(mdPlugin({ mode: [Mode.HTML, Mode.TOC, Mode.REACT] }));
    config.plugins.push(
      svgrPlugin({
        svgrOptions: {
          icon: false,
        },
      }),
    );
    return config;
  },
};

Thanks for the help

Router links

When creating a link via markdown syntax ([display](href)) to a known route in vue-router or react-router, there should be an option to prefer <router-link> (vue) or <Link> (react) instead of <a>.

It should turn this

[Home](/home)

Into this (vue)

<router-link to="/home">Home</router-link>

Or this (react)

<Link to="/home">Home</Link>

From a quick look at the code, this might not be entirely possible with the current design, but I would be happy to be able to provide my own components to override tags. Right now, passing in a custom component to bridge <a> to <router-link> via VueComponentWith({A: MyTag}) doesn't seem to work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.