brillout / vite-plugin-mdx

Vite Plugin for MDX
MIT License
115 stars 36 forks source link

Support custom package #24

Closed sskyy closed 3 years ago

sskyy commented 3 years ago

There are many other frameworks need vite and mdx. This PR adds an option to support custom framework.

brillout commented 3 years ago

I thought MDX only supports React, Preact and Vue?

sskyy commented 3 years ago

I thought MDX only supports React, Preact and Vue?

It can be easily extended to support any framework. Checkout https://github.com/ariesate/engine/tree/master/packages/mdx-axii for example. Axii is a framework I wrote, I want to use mdx with vite, so I created this PR. I think there maybe other frameworks like Inferno may also need too.

aleclarson commented 3 years ago

Maybe a better option (from a user perspective) is to fork vite-plugin-mdx, have it use axii instead of react/preact and publish it as @axii/vite-plugin-mdx. Then users won't need to inject the Axii-specific imports manually.

brillout commented 3 years ago

If we find a better option name - transformOption.inject and transformOption.package is not particularly explicit here - then I think it'd be nice to merge this. Since the plugin is already React/Preact(/Vue) agnostic, this fits well.

aleclarson commented 3 years ago

I'm not a fan of forcing users to explicitly configure stuff when it can be avoided.

We could provide a Vite hook for vite-plugin-axii to implement.

export default () => {
  return {
    name: 'vite-plugin-axii',
    mdxGetImports(resolveImport) {
      if (resolveImport('axii')) {
        if (!resolveImport('mdx-axii')) {
          throw Error('Must install mdx-axii')
        }
        return [
          `import {createElement} from "axii"`,
          `import {mdx} from "mdx-axii"`,
        ]
      }
    }
  }
}

Or we could provide another export for defining custom imports.

import mdx from 'vite-plugin-mdx'

const mdxAxii = mdx.withImports({
  axii: ['createElement'],
  'mdx-axii': ['mdx'],  
})

export default {
  plugins: [
    mdxAxii({ /* mdx options */ }),
  ]
}

With either option, you could have an @axii/vite-plugin-mdx package that wraps this plugin, avoiding the need to fork.

import mdx from 'vite-plugin-mdx'

export default mdx.withImports({
  axii: ['createElement'],
  'mdx-axii': ['mdx'],
})
sskyy commented 3 years ago

I forked vite-plugin-mdx and closing this pr for now. I'm happy to help when you have a final design to support this feature.

brillout commented 3 years ago

@aleclarson Good idea

aleclarson commented 3 years ago

Fixed in #25