GlobalVueStyles: not working for global Sass in vue components

Viewed 619

I am trying to load a global sass variable file into my Vue style tags. If I am understanding globalVueStyles right, this should Indicate a file to include in every component style. But when I set it up it seems to not do anything and when I run npm run dev I get an undefined variable error.

Here is my laravel mix code:

mix.js('resources/js/app.js', 'public/js')
    .vue()
    .sass('resources/sass/main.scss', 'public/css')
    .options({
        extractVueStyles: true,
        globalVueStyles: 'resources/sass/utils/_variables.scss',
    })
    .version()

after doing this I thought I should have access to my variables in my .vue files by doing this:

<template>
    <h1>Example Component hi test</h1>
</template>

<script>
export default {

}
</script>
    
<style lang="scss">
    h1 {
        font-size: 50px;
        color: $blue;
    }
</style>

And here is the error I am getting:

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined variable.
  ╷
4 │    color: $blue;
  │           ^^^^^
  ╵
  resources/js/components/HelloWorld.vue 4:11  root stylesheet

I'm sure I'm missing something, but any help on this would be appreciated.

2 Answers

When I tried your solution it did not work. Here is how I managed to fix this issue, using this new/changed property additionalData, in previous versions this property was data or prependData.

mix.webpackConfig({
    module: {
        rules: [
            {
                test: /\.scss$/,
                use: [
                    {
                        loader: "sass-loader",
                        options: {
                            additionalData: `@import "@/_variables.scss";
                            @import "@/_mixins.scss";
                            @import "@/_extends.scss";
                            @import "@/_general.scss";`
                        },
                    },
                ],
            }
        ]
    },
    resolve: {
        alias: {
            '@': path.resolve('resources/sass'),
            '~': path.resolve('/resources/js'),
            'Vue': 'vue/dist/vue.esm-bundler.js',
        }
    },
    output: {
        chunkFilename: '[name].js?id=[chunkhash]',
    },
});

mix.js('resources/js/app.js', 'public/js').vue()
    .sass('resources/sass/app.scss', 'public/css')
    .copyDirectory('resources/images', 'public/images');


if (mix.inProduction()) {
    mix.version();
}

Note that alias for path 'resources/scss' is "@". I hope this saved someone some time :)

Related