browserify/vueify: inject global scss file in all components

228 Views Asked by At

In an app I am using browserify and vueify. I am trying to inject global scss file (with variables, mixins, colors etc..) into Vue to make it available for all components (instead to have the file explicitly imported in each components).

I have the following main.scss at path public/app/styles/main.scss:

// public/app/styles/main.scss

// Helpers
@import "helpers/mixins";
@import "helpers/variables";
@import "helpers/colors";


// Base
@import "base/reset";
@import "base/typography";
@import "base/base";


// Layout
@import "base/layout";

In the gulp.js file I have the following:

// gulp.js

gulp.task("build_js", () => {

    return browserify({
        entries: config.app.index,
        cache: {},
        dev: true
    })
        // [...]
        .transform(vueify, {
            sass: {
                includePaths: ["public/app/styles", "public/app/styles/main.scss"]
            }
        })
        // [...]

});

This is the App.vue component where I've tried to use a global defined scss variable:

<!--App.vue-->

<template>

    <div id="app"></div>

</template>

<script>

    export default {

        name: "App"

    }

</script>

<style scoped lang="scss">

    #app {
        width: 100%;
        height: 100%;
        background-color: $backgroundColor;        
    }

</style>

But I got the following error:

Error: Undefined variable: "$backgroundColor". while parsing file: D:\Users\revy\Documents\myapp\public\app\components\App.vue

What am I doing wrong?

1

There are 1 best solutions below

1
On

The issue is that your variable $backgroundColor has not been defined. Most likely, the file that defines it has not been bundled.

You can solve that by importing your main.scss file in the component style block, and it should be resolved.

<!--App.vue-->

<template>

    <div id="app"></div>

</template>

<script>

    export default {

        name: "App"

    }

</script>

<style lang="scss" src="public/app/styles/main.scss"></style>
<style scoped lang="scss">

    @import "public/app/style/main.scss";

    #app {
        width: 100%;
        height: 100%;
        background-color: $backgroundColor;        
    }

</style>

You might have to change the path, as I am not sure what your files structire looks like.

However if the import doesn't work, You can try including the file directly from the component using a style tag with a src attribute :

<!--App.vue-->

<template>

    <div id="app"></div>

</template>

<script>

    export default {

        name: "App"

    }

</script>

<style lang="scss" src="public/app/styles/main.scss"></style>
<style scoped lang="scss">

    #app {
        width: 100%;
        height: 100%;
        background-color: $backgroundColor;        
    }

</style>

With this syntax, the bundler will load the SCSS file directly and resolve all the imports within.