A Nuxt module by drunomics for previewing Vue components in external contexts (like iframes or separate HTML pages). Originally developed for use with decoupled Drupal environments, but can be used with any backend.
- 🎭 Component Preview Mode: Conditionally render components for previewing in isolation
- 🚀 Production Safe: Inactive by default, only activates when explicitly enabled
- 🎯 Target Rendering: Render components to specific DOM elements using CSS selectors
- 🧪 Testing Ready: Comprehensive test coverage and playground setup
Install the module to your Nuxt application:
npm install nuxt-component-preview
Add it to your nuxt.config.ts
:
export default defineNuxtConfig({
modules: [
'nuxt-component-preview',
],
// Optionally configure here
// componentPreview: { ... }
})
To render a component preview, use the <ComponentPreviewArea />
component in your app.
Example app.vue
<template>
<ComponentPreviewArea v-if="useRuntimeConfig().public.componentPreview" />
<NuxtPage v-else />
</template>
Important: Then, when rendering outside of a Nuxt app (e.g., in a static HTML file or external context), you must manually set the runtime config on window.__NUXT__
before loading the Nuxt entry script to activate it. See the playground/public/preview-test.html for a working example.
<script>
window.__NUXT__ = window.__NUXT__ || {};
window.__NUXT__.config = {
public: {
componentPreview: true
}
};
</script>
You can then load the Nuxt entry script as shown in preview-test.html.
This setup is ideal for integrating with a Drupal backend (or any backend) that needs to render Nuxt components in isolation, such as for CMS previews or design systems.
Example: Rendering a component preview via JavaScript
You can use the $previewComponent
method on the Nuxt app instance to dynamically render a component into a target element. For example, in a static HTML file:
<script>
window.addEventListener('nuxt-component-preview:ready', (event) => {
const { nuxtApp } = event.detail;
console.log('Nuxt Component Preview is ready!');
// Preview TestMarkup component
nuxtApp.$previewComponent(
'TestMarkup',
{
content: `
<div style="color: blue;">
<h2>Rendered HTML Content</h2>
<p>This is <strong>HTML</strong> content rendered through the TestMarkup component.</p>
</div>
`
},
'#preview-target-1'
);
// ...more examples in preview-test.html
});
</script>
See playground/public/preview-test.html for a full working example including multiple components and targets.
This module includes comprehensive tests. To run them:
npm run test
Run command
npm run release -- --release-as 1.0.0-alpha.1
This module is maintained by drunomics and inspired by the needs of decoupled Drupal projects, such as nuxtjs-drupal-ce.