Skip to Content
The Public InterfaceSeptember 12, 2026

The Public Interface

June 28, 2024

Transform Markdown into JavaScript with a Vite Plugin

How to use the transform hook in a Vite plugin to import markdown files into modules, converting them to HTML strings.

By Ross Robinojavascript / vite

In this tutorial, I’ll show you how you can use the transform hook within a Vite plugin. We’ll create a way to import markdown files into JavaScript modules as a parsed HTML string.

If you haven’t created a plugin before, check out this tutorial: Create Your Own Vite Plugin.

First, install marked as a dependency, we’ll use it to convert our markdown into HTML.

We will use Rollup’s transform hook within our plugin, it allows us to import files that are not JavaScript by first compiling them to a module within the plugin. Lots of frameworks make use of this hook if they use custom file types. For example, vite-plugin-svelte uses this hook to convert .svelte files into JavaScript.

We’ll follow the example from the Vite documentation and create our markdown plugin. Let’s create a new plugin called markdown that converts .md files to JavaScript by adding it to our plugins array.

Next, since I’m using TypeScript, I need to also tell the TypeScript language server that markdown files can now be imported. Since all files within src are included in our tsconfig, we can add a declaration file anywhere inside src to declare markdown files as modules.

This marks all .md files as modules that export an object containing html and md strings.

Next, create a .md file within your project to import.

Then test out the functionality within main.ts.

Run npm run dev to start the dev server and see the markdown rendered on the page!

It’s important to note, this import occurs at build time. Run npm run build to build your project and then inspect the dist/assets/index...js file. You’ll see the processed HTML inlined into this JavaScript file.

Utilize Rollup’s transform hook within a plugin to compile non-JS files into modules at build time.

Thanks for reading!…

Continue reading

In brief

Create Your Own Vite Plugin

Understand modern development tooling by building a basic Vite plugin with LinkeDOM.

In this post, I’ll show you how you can create a Vite plugin to reuse HTML partials in your web development projects. Vite is a popular JavaScript bundler and development server, it also has a plugin system has become a large part of the JavaScript ecosystem. These plugins allow developers to add additional functionality to Vite’s build and development pipeline.

June 7, 2024