To resolve the issue with importing CommonJS modules in a Vite project, you can use the vite-plugin-commonjs plugin to handle CommonJS modules properly. Here's a step-by-step solution to your problem:
-
Install the
vite-plugin-commonjsplugin:First, you need to install the
vite-plugin-commonjsplugin. You can do this using npm or yarn:npm install vite-plugin-commonjs --save-devor
yarn add vite-plugin-commonjs --dev -
Configure Vite to use the plugin:
Next, you need to configure Vite to use the
vite-plugin-commonjsplugin. Update yourvite.config.jsfile as follows:import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import commonjs from 'vite-plugin-commonjs'; export default defineConfig({ plugins: [ vue(), commonjs() ] }); -
Import the CommonJS module in your Vue component:
Now, you can import the
markdown-it-attrsplugin in your Vue component. Sincemarkdown-it-attrsusesmodule.exports, you need to handle it properly. Here's an example of how you can do it:<template> <div v-html="renderedMarkdown"></div> </template> <script setup> import { ref, onMounted } from 'vue'; import MarkdownIt from 'markdown-it'; const renderedMarkdown = ref(''); onMounted(async () => { const MarkdownItAttrs = await import('markdown-it-attrs').then(module => module.default || module); const md = new MarkdownIt(); md.use(MarkdownItAttrs); const markdownContent = '# Hello World\n{.class}'; renderedMarkdown.value = md.render(markdownContent); }); </script> -
Run your Vite project:
Finally, run your Vite project to see the changes:
npm run devor
yarn dev
By following these steps, you should be able to resolve the issue with importing CommonJS modules like markdown-it-attrs in your Vite project. The vite-plugin-commonjs plugin helps Vite handle CommonJS modules properly, allowing you to use them seamlessly in your project.