sass scss vue安装和使用

来源:www.npmjs.com 更新时间:2023-05-25 21:55

一、首先说明sass和scss的区别。

1、异同:1)简言之可以理解scss是sass的一个升级版本,完全兼容sass之前的功能,又有了些新增能力。语法形式上有些许不同,最主要的就是sass是靠缩进表示嵌套关系,scss是花括号

     2)文件扩展名不同,Sass 是以“.sass”后缀为扩展名,而 SCSS 是以“.scss”后缀为扩展名

     3)语法书写方式不同,Sass 是以严格的缩进式语法规则来书写,不带大括号({})和分号(;),而 SCSS 的语法书写和我们的 CSS 语法书写方式非常类似。

 
//sass 
.father
    data-width:100px;
    .son
        data-width:50px;
//scss 
.father{
    data-width:100px;
    .son{
        data-width:50px;
    }
}       
 

2、 scss功能很强大的样子,能做运算、写函数啥的,但是我只是作为语法糖用而已,只看了些基础功能 
我个人常用的功能有:

    • 嵌套
    • 变量 $color : #111111;
    • 混入 @mixin
    • 继承 @extend

3、一个关于@mixin、@extend、%placeholder的适用场景总结

  • mixin 可以传变量
  • extend 不可以传变量,相同样式直接继承,不会造成代码冗余;基类未被继承时,也会被编译成css代码
  • placeholder 基类未被继承时不会被编译成css代码

二、

1、开始在vue项目中使用sass,在命令行输入一下命令进行安装(使用git命令行要用shift+insert 进行粘贴否则粘贴不上)

cnpm install node-sass --save-dev
cnpm install sass-loader --save-dev
cnpm install style-loader --save-dev

2. 这个时候你打开build文件夹下面的webpack.base.config.js
把里面的module改成这样的

 
module: { 
    rules: [ 
          { 
            test: /\.vue$/, 
            loader: 'vue-loader', 
            options: vueLoaderConfig
          }, 
          { 
            test: /\.js$/, 
            loader: 'babel-loader', 
            include: [resolve('src'), 
            resolve('test')] 
          }, 
          {
             test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, 
             loader: 'url-loader', 
             options: { 
                limit: 10000,
                 name: utils.assetsPath('img/[name].[hash:7].[ext]')
                             } 
                 }, 
          { 
                    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                    loader: 'url-loader', 
                   options: { 
                               limit: 10000, 
                               name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
                            } 
                   }, 
          { //从这一段上面是默认的!不用改!下面是没有的需要你手动添加,相当于是编译识别sass! 
                     test: /\.scss$/,
                     loaders: ["style", "css", "sass"]
                  } 
               ] 
           }
 

3.在需要用到sass的地方添加lang=scss

 <style lang="scss" scoped="" type="text/css"> 
//你的sass语言 $primary-color: #333; 
   body {
        color: $primary-color; //编译后就成了 color:#333;类似于js的变量! 
       } 
</style>

sass的一些其它用法可以查看官网!

 



 

Sass Loader

Loads a Sass/SCSS file and compiles it to CSS.

Use the css-loader or the raw-loader to turn it into a JS module and the ExtractTextPlugin to extract it into a separate file. Looking for the webpack 1 loader? Check out the archive/webpack-1 branch.

Install


 
npm install sass-loader node-sass webpack --save-dev

The sass-loader requires node-sass and webpack as peerDependency. Thus you are able to control the versions accurately.

Examples

Chain the sass-loader with the css-loader and the style-loader to immediately apply all styles to the DOM.


 
npm install style-loader css-loader --save-dev

 
// webpack.config.js
module.exports = {
    ...
    module: {
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader" // creates style nodes from JS strings
            }, {
                loader: "css-loader" // translates CSS into CommonJS
            }, {
                loader: "sass-loader" // compiles Sass to CSS
            }]
        }]
    }
};

You can also pass options directly to node-sass by specifying an options property like this:


 
// webpack.config.js
module.exports = {
    ...
    module: {
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader",
                options: {
                    includePaths: ["absolute/path/a", "absolute/path/b"]
                }
            }]
        }]
    }
};

See node-sass for all available Sass options.

In production

Usually, it's recommended to extract the style sheets into a dedicated file in production using the ExtractTextPlugin. This way your styles are not dependent on JavaScript:


 
const ExtractTextPlugin = require("extract-text-webpack-plugin");
 
const extractSass = new ExtractTextPlugin({
    filename: "[name].[contenthash].css",
    disable: process.env.NODE_ENV === "development"
});
 
module.exports = {
    ...
    module: {
        rules: [{
            test: /\.scss$/,
            use: extractSass.extract({
                use: [{
                    loader: "css-loader"
                }, {
                    loader: "sass-loader"
                }],
                // use style-loader in development
                fallback: "style-loader"
            })
        }]
    },
    plugins: [
        extractSass
    ]
};

Usage

Imports

webpack provides an advanced mechanism to resolve files. The sass-loader uses node-sass' custom importer feature to pass all queries to the webpack resolving engine. Thus you can import your Sass modules from node_modules. Just prepend them with a ~ to tell webpack that this is not a relative import:


 
@import "~bootstrap/dist/css/bootstrap";

It's important to only prepend it with ~, because ~/ resolves to the home directory. webpack needs to distinguish between bootstrap and ~bootstrap because CSS and Sass files have no special syntax for importing relative files. Writing @import "file" is the same as @import "./file";

Problems with url(...)

Since Sass/libsass does not provide url rewriting, all linked assets must be relative to the output.

  • If you're just generating CSS without passing it to the css-loader, it must be relative to your web root.
  • If you pass the generated CSS on to the css-loader, all urls must be relative to the entry-file (e.g. main.scss).

More likely you will be disrupted by this second issue. It is natural to expect relative references to be resolved against the .scss file in which they are specified (like in regular .css files). Thankfully there are a two solutions to this problem:

Extracting style sheets

Bundling CSS with webpack has some nice advantages like referencing images and fonts with hashed urls or hot module replacement in development. In production, on the other hand, it's not a good idea to apply your style sheets depending on JS execution. Rendering may be delayed or even a FOUC might be visible. Thus it's often still better to have them as separate files in your final production build.

There are two possibilities to extract a style sheet from the bundle:

Source maps

To enable CSS source maps, you'll need to pass the sourceMap option to the sass-loader andthe css-loader. Your webpack.config.js should look like this:


 
module.exports = {
    ...
    devtool: "source-map", // any "source-map"-like devtool is possible
    module: {
        rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader", options: {
                    sourceMap: true
                }
            }, {
                loader: "sass-loader", options: {
                    sourceMap: true
                }
            }]
        }]
    }
};

If you want to edit the original Sass files inside Chrome, there's a good blog post. Checkout test/sourceMap for a running example.

Environment variables

If you want to prepend Sass code before the actual entry file, you can set the data option. In this case, the sass-loader will not override the data option but just append the entry's content. This is especially useful when some of your Sass variables depend on the environment:


 
{
    loader: "sass-loader",
    options: {
        data: "$env: " + process.env.NODE_ENV + ";"
    }
}

Please note: Since you're injecting code, this will break the source mappings in your entry file. Often there's a simpler solution than this, like multiple Sass entry files.

 

  

  .box{

  

  data-width: 100%;

  

  :hover{

  

  color: red;

  

  } }