Search code examples
vue.jssassvue-componentbulma

How to inject Global constant to a vue component <style>?


I'm searching how to inject a global (THEME_NAME in my example) to all the vue components:

<template>..</template>
<style lang="scss">
    @import "bulmaswatch/<%=THEME_NAME=>/bulmaswatch.scss";

    .foo {
      color: $primary;
    }
</style>

Context:

I'm using the darkly theme of bulma css in my vue application (vue Cli 3)

<template>..</template>
<style lang="scss">
    @import "bulmaswatch/darkly/bulmaswatch.scss";
    .foo {
        color: $primary;
    }
</style>

In order to switch to the cyborg theme, I will have to replace darkly with cyborg everywhere...

Is there a better way? Something like

<template>..</template>
<style lang="scss">
    @import "bulmaswatch/<%=THEME_NAME=>/bulmaswatch.scss";

    .foo {
      color: $primary;
    }
</style>

then somewhere in Webpack or vue.config.js, we can decide what is the theme

configureWebpack: () => {
    return {
        plugins: [
            new webpack.DefinePlugin({
                THEME_NAME: "cyborg"
            }),
        ],
    }
}

Solution

  • In order to switch to the cyborg theme, I will have to replace darkly with cyborg everywhere...

    Not if you use the re-export pattern. There's no need for any external libraries and codegen magics with webpack.

    Basically, you create a file where you import your theme. Let's call it _my-bulma-theme.scss and let's import darkly for now.

    // _my-bulma-theme.scss
    @import "bulmaswatch/darkly/bulmaswatch.scss";
    

    In your code, you import this file instead of importing from Bulma directly:

    // some-component.vue
    <style>
      @import "../../my-bulma-theme";
    </style>
    
    // some-other-component.vue
    <style>
      @import "../../my-bulma-theme";
    </style>
    

    Now, when you want to change the theme, you just need to change it in one place: the _my-bulma-theme.scss file.

    // _my-bulma-theme.scss
    @import "bulmaswatch/cyborg/bulmaswatch.scss";