详解Vue2 添加对scss的支持

引入loader

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

scss支持

为了使用scss,我们需要先安装相关的node包:

npm install --save style-loader sass-loader node-sass file-loader

安装好之后,为了可以在.vue和.scss中使用,需要在webpack.config.js中配置对应的解析器:

var webpack = require('webpack');
module.exports = {
  entry: ['./src/entry.js'],
  output: {
    path: __dirname,
    filename: 'build/main.js'
  },
  resolve: {
    alias: {
      'vue': 'vue/dist/vue.js'
    }
  },
  module: {
    loaders: [{
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            scss: 'style-loader!css-loader!sass-loader'
          }
        }
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },{
        test: /\.css$/,
        loader: ['style-loader', 'css-loader']
      }, {
        test: /\.scss$/,
        loader: ['style-loader', 'css-loader', 'sass-loader']
      }, {
        test: /\.(png|jpg|jpeg|gif|bmp)$/,
        loader: ['file-loader?limit=7000&name=build/assets/[name].[ext]']
      }
    ]
  }
};

关于上面resolve的配置,是因为编译和打包源文件默认不一样。

测试scss

打开PageTwo.vue测试一下:

<style lang="scss" scoped>
section {
 & > div {
  font-size: 20px;
 }
}
</style>

编译正常。

本篇最终项目文件Github地址:github.com/yelloxing/vue.quick/tree/V6

相关推荐