☝️Small business or a startup? See if you qualify for our special offer.
+

Dynamically Importing Theme CSS from node_modules in Vue.js

Answered
Mor asked 4 days ago

Hi,

I'm working on a Vue.js project where I need to dynamically load theme CSS files from node_modules at runtime.

I'm currently doing this by importing the CSS file (import 'flexmonster/theme/purple/flexmonster.css'), which works fine initially. However, I want to switch themes dynamically, so I tried removing the <link> or <style> tag that was added by Webpack and then re-importing a different theme.

Here's what I’ve noticed:

  • After removing the existing tag and trying to re-import the same CSS file again, no new tag is created, and the styles aren’t applied, how can I handle it?

  • If I import multiple CSS files, the styles overwrite each other.

What’s the recommended approach for switching between multiple external themes dynamically (especially from node_modules) in Vue.js?

1 answer

Public
Maksym Diachenko Maksym Diachenko Flexmonster 22 hours ago

Hello,

Thank you for reaching out to us and providing a detailed explanation.

Your idea of changing a <link> tag with styles is completely valid, as this approach gives you full control over styles at runtime. A possible way to implement a dynamic theme switch in Vue is by using this approach:

<script>
export default {
  name: "PivotTableDemo",
  methods: {
    changeTheme(theme) {
      // Remove the existing theme stylesheet
      const existingThemeLink = document.getElementById("theme-stylesheet");
      if (existingThemeLink) {
        existingThemeLink.parentNode.removeChild(existingThemeLink);
      }
      // Add the new theme stylesheet
      const link = document.createElement("link");
      link.id = "theme-stylesheet";
      link.rel = "stylesheet";
      link.href = `/themes/${theme}/flexmonster.css`;
      document.head.appendChild(link);
    },
  },
};
</script>

<template>
  <div>
    <button @click="changeTheme('default')">Default Theme</button>
    <button @click="changeTheme('green')">Green Theme</button>
    <button @click="changeTheme('dark')">Dark Theme</button>
    <Pivot
      height="600"
      report="https://cdn.flexmonster.com/github/demo-report.json"
      _v-bind:licenseKey="'XXXX-XXXX-XXXX-XXXX-XXXX'"
    />  
  </div>
</template>

However, for this to work, you need to make sure that the CSS theme files from node_modules (e.g., flexmonster/themes/...) are available as static assets in your production build.

You can check the sample project with the dynamic theme change in the attachments.

Please let us know if you need any further assistance.

Best Regards,
Maksym

Please login or Register to Submit Answer