I got a rather simple problem with a VueJS component that needs to use a variable. The problem comes with getting sass to register variables inside a component.
I tried importing the _variables.scss
file containing my variables but to no luck. At this point any guidance is very much appreciated, or if there is another way for a component to inherit styling.
<template> <div class="my-color"></div> </template> <style lang="sass"> .my-color { color: $primary-color; } </style> <script> export default{ data(){ return {} } } </script>
var elixir = require('laravel-elixir'); require('laravel-elixir-vueify'); elixir(function(mix) { mix.browserify('main.js'); mix.sass('app.scss'); });
@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap"; @import "modules/variables";
$primary-color: #BA2731; //Red
Vue CLI install Once installed, create a folder called sass , scss or styles in your src directory with a file named variables. scss or variables. sass . The vuetify-loader will automatically bootstrap your variables into Vue CLI's compilation process, overwriting the framework defaults.
Vue CLI projects come with support for PostCSS, CSS Modules and pre-processors including Sass, Less and Stylus.
To make Sass (or, specifically, SCSS in this case) variables available to JavaScript, we need to “export” them. The :export block is the magic sauce webpack uses to import the variables. What is nice about this approach is that we can rename the variables using camelCase syntax and choose what we expose.
Importing the _variables.scss
in every component seems to be the only solution I've found so far (it should work, according to this issue).
<template> <div class="my-color"></div> </template> <style lang="sass"> @import 'path/to/your/_variable.scss'; // Using this should get you the variables .my-color { color: $primary-color; } </style> <script> export default{ data(){ return {} } } </script>
As you are only going to include variables, this shouldn't be a problem.
But as mentioned in the issue, a word of caution: You should only include abstract entities (variables, extends, mixins) into every component, no concrete CSS rules.
Assuming you are using vue-cli, try this.
If you don't already have the sass loader installed:
npm install -D sass-loader node-sass
Then in vue.config.js
:
const path = require('path'); module.exports = { css: { loaderOptions: { sass: { data: `@import "@/pathto/variables.scss";` } } } };
In your component:
<style lang="sass"> .my-color { color: $primary-color; } </style>
Source:
Passing options to pre-processor loaders
How to import a sass file into every vue component
Edit:
As of sass-loader 8, data
needs to be prependData
(Thanks to @ben-y for pointing this out):
const path = require('path'); module.exports = { css: { loaderOptions: { sass: { prependData: `@import "@/pathto/variables.scss";` } } } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With