vue项目中使用scss

我不是女神ヾ 2023-02-20 12:22 70阅读 0赞

vue项目中使用scss

随着sass / less等css预器的出现,编写css变的越来越有乐趣。所以现在越来越多的人在项目中喜欢使用scss或者less。(我自己就是一个)。由于最近在所以最近的博客应该都会和vue有关。今天要和大家分享的就是如何在vue项目中约会scss(以前less也类似) )

二vue中约会scss

2.1 vue-loader

在讲如何在vue项目中使用scss之前,我们先来简单了解一个概念,那就是vue-loader。vue-loader是什么东西呢?vue-loader实际上就是一个webpack的loader。所以我们如果要想再vue项目中使用scss,肯定要告诉vue-loader怎么样解析我的scss文件。
不了解webpack的同学可以先去自行百度。我这里就放一张图,看完大家可以也可以知道webpack能做些什么事情了。

webpack作用

2.2加载器配置

在webpack中,所有预装器都要配合相应的加载器,vue-loader允许其他的webpack-loader处理组件中的一部分吗,然后它根据lang属性自动判断出要使用的加载器。所以,实际上只要安装处理sass / scss的加载器。可以在vue中使用scss了。
现在我们来安装sass / scss加载器

  1. npm install sass-loader node-sass --save-dev

2.3为什么无需配置

我们前面说到,vue-loader提供能根据语言属性自动判断出要使用的loaders。它是怎么样做到的?有这么神奇嘛?我们下面来看一看最核心部分的源代码

  1. exports.cssLoaders = function (options) {
  2. options = options || { }
  3. var cssLoader = {
  4. loader: 'css-loader',
  5. options: {
  6. minimize: process.env.NODE_ENV === 'production',
  7. sourceMap: options.sourceMap
  8. }
  9. }
  10. // generate loader string to be used with extract text plugin
  11. function generateLoaders (loader, loaderOptions) {
  12. var loaders = [cssLoader]
  13. if (loader) {
  14. loaders.push({
  15. loader: loader + '-loader',
  16. options: Object.assign({ }, loaderOptions, {
  17. sourceMap: options.sourceMap
  18. })
  19. })
  20. }
  21. // Extract CSS when that option is specified
  22. // (which is the case during production build)
  23. if (options.extract) {
  24. return ExtractTextPlugin.extract({
  25. use: loaders,
  26. fallback: 'vue-style-loader'
  27. })
  28. } else {
  29. return ['vue-style-loader'].concat(loaders)
  30. }
  31. }
  32. // https://vue-loader.vuejs.org/en/configurations/extract-css.html
  33. return {
  34. css: generateLoaders(),
  35. postcss: generateLoaders(),
  36. less: generateLoaders('less'),
  37. sass: generateLoaders('sass', { indentedSyntax: true }),
  38. scss: generateLoaders('sass'),
  39. stylus: generateLoaders('stylus'),
  40. styl: generateLoaders('stylus')
  41. }
  42. }

就是上述这段代码让vue-loader具有这种能力,它会根据不同的文件去使用不同的loader

2.4使用scss

这样你就可以愉快的使用scss了。

  1. <style scoped lang="sass">
  2. xxxx
  3. xxxx
  4. </style>

发表评论

表情:
评论列表 (有 0 条评论,70人围观)

还没有评论,来说两句吧...

相关阅读

    相关 vue 使用scss

    一、概述 CSS 预处理器 SCSS是一种CSS预处理语言,定义了一种新的专门的编程语言,编译后形成正常的css文件,为css增加一些编程特性,无需考虑浏览器的兼容