欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

vue中引入全局scss变量

程序员文章站 2022-06-27 14:21:45
...

第一: 问题    

先说一说为什么会碰到这个问题?

    当我在尝试进行动态换肤的时候,发现只有部分组件的样式会变,但是我写的div不会变,那么就尝试在main.js中引入了scss样式文件,想要尝试通过js来控制scss变量值的变化,以期望用另一种方式即js控制scss变量值的方式实现换肤,此时就先要解决在vue组件中能够使用scss文件中的变量,进行了如下尝试:

vue中引入全局scss变量

此时此时在其他的vue组件中使用scss文件中定义的变量$--color-primary是无效的,并且报错如下

vue中引入全局scss变量

第二: 问题解决尝试

参考链接:

通过 sass-resources-loader 全局注册 Sass 变量

Vue引入sass并配置全局变量

1、npm install --save-dev sass-resources-loader

2、在build--> utils.js 中的exports.cssLoaders中新增一个函数并修改return中的变量

function generateSassResourceLoader () {
    var loaders = [
      cssLoader,
      'sass-loader',
      {
        loader: 'sass-resources-loader',
        options: {
          resources: [
// 这里面放的是样式的数组
// generateSassResourceLoader函数中的'../src/styles/element-variables.scss' 是你的scss文件路径和文件名
            path.resolve(__dirname, '../src/styles/element-variables.scss'),
          ]
        }
      }
    ]
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }
 return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateSassResourceLoader(),
    scss: generateSassResourceLoader(),
    /*scss: generateLoaders('sass').concat({
      loader: 'sass-resources-loader',
      options: {
        resources: path.resolve(__dirname, '../src/styles/element-variables.scss') //这里是单独建的存放变量的scss
      }
    }),*/
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }

 

3、最终修改的位置如图:

vue中引入全局scss变量

  

4、配置完成后重启项目,就可以在项目中直接使用了,而且也可以不在main.js中进行引用。

但是此处可能仍然存在问题,使用 @mixin、% 定义的通用样式未被继承不会被解析产生相应的 css,则不会冗余,那么$变量的话可能仍然是有冗余的,这个待确认。

备注:sass-resources-loader tips

上面链接中提示了几点注意点粘贴在此:

  • Do not include anything that will be actually rendered in CSS, because it will be added to every imported SASS file.
  • Avoid using SASS @import rules inside resources files as it slows down incremental builds. Add imported files directly in sassResources array in webpack config instead. If you concerned about location of your resources index, you might want to check out the solution outlined in this comment.
  • If you still want to use SASS @imports make sure your paths are relative to the file they defined in (basically, your file with resources), except the ones started with ~ (~ is resolved to node_modulesfolder).

以上为学习内容笔记,如能帮忙解答小尾巴非常感谢。