前两天,在作项目的时候,我使用了在Gruntfile.js配置compass,经过compass来编译个人sass文件。开始sass文件编译一切OK,可是到后面我使用了compass的sprites这个功能,原本图片整合这些都没有什么问题。但是我在页面里怎么都看不见整合的图片,查看以后原来是图片的路径生成问题。compass把这个自动生成的sprite image 在编译后的css文件中是绝对路径,这样就致使了我在页面中看不见这个图片。css
因为以前我使用compass是用koala来自动编译,也是使用koala自动生成一个config.rb配置文件。因此就没有遇到这个输出相对路径和绝对路径的问题。node
查询以后在Gruntfile.js中的compass 任务里配置上使用相对路径输出(relativeAssets:true)这个参数,而后一切都正常了。下面使用github上面的代码块来讲明一下:git
grunt.initConfig({ compass: { // Task dist: { // Target options: { // Target options sassDir: 'sass', //sass文件目录 cssDir: 'css', //输出css的目录 environment: 'production',//生产环境 relativeAssets: true //使用相对路径输出 } } } });
以防下次再遇到由于参数配置而致使一些问题,因此我就在参考了一些文章以后,将在Gruntfiel.js中配置compass任务的一些参数作了一些总结,如下多数为翻译过来的内容github
首先你须要安装node.js, grunt.js, Ruby, SASS 和 Compassnpm
1.首先须要安装这个插件缓存
$ npm install grunt-compass --save-dev
2.在Gruntfile.js中调用这个插件sass
grunt.loadNpmTasks( 'grunt-compass' )
3.在Gruntfile.js配置watch任务,当在命令行输入grunt watch 命令来监听sass文件时,若是sass文件有改变就会运行这个tasksruby
watch: { files: [ 'assets/scss/*.scss' ], tasks: [ 'compass:dev', 'compass:prod' ] }
下面就是配置compass任务koa
4.设置sass和css路径grunt
src: 'assets/scss', //sass文件所在目录
dest: 'assets/css' //编译后输出css的目录
5.指定你想编译的某一个文件
单个文件:
specify: 'assets/scss/base.scss'
使用通配符来匹配文件:
specify: 'assets/scss/*.scss' // 匹配全部 `assets/scss` 目录下的以.scss后缀名结尾的sass文件,可是不匹配子目录下的sass文件 specify: 'assets/scss/**/*.scss' // 匹配全部'assets/scss'目录下的全部以.scss后缀名结尾的sass文件,包括其子目录的全部.scss文件
注意:.sass/.scss文件会忽略文件名如下划线 _ 开头的文件。全部的文件都必须在你在 src 指定的目录下面
6.使用 bathPath 指定运行compass的位置,这对多个项目分开的文件夹结构使用grunt很是有用。
basePath: 'path/to/project/'
7.像这样设置你本身输出css的习惯:
outputstyle: 'compressed' //压缩的格式。其余的输出风格还有:nested、expanded、compact
8.取消行注释
noLineComments:false //这是个Boolean类型
9.运行命令以前须要一个Ruby库,这个一般是用于一个没有项目配置文件的compass 插件
require: 'animate-sass'
或者
require: [ 'animate-sass', 'mylib' ]
10.设置compass 帮助器生成一个相对路径的资源(例如使用compass的sprites)
relativeassets: true
11.若是你有compass的配置文件能够直接使用,还能够在Gruntgile.js从新设置配置文件里面的配置,或者新加其余的配置项
config: '/path/to/config'
重写配置文件里面的配置
config: '/path/to/config',// css_dir = 'dev/css' cssDir: 'dist/css' //重写输出css目录
注意:若是你不使用绝对路径,要使用相对路径的话,那就是相对于包含Gruntfile.js的目录。
12.若是有你compass配置文件,那你能够在config.rb文件中设置环境变量
environment: 'production'
而后在config.rb文件中像这样用:
output_style = ( environment == :production ) ? :compressed : :expanded
13.你能够添加一个本身定制的 importPath 文件夹,让在sass文件中的 @import 指令可以找到
importPath: '/path/to/importPath'
14.移除已经生成的文件和sass的缓存
有时候须要为生产环境从新编译一次,执行 compass clean就比用 --force 编译更快一些。如今你就能够开始 grunt compass-clean 任务,gruntfile文件中还能够这样:
grunt.registerTask( 'prod', [ 'compass-clean', 'compass:prod' ] );
compass: { dev: { src: 'assets/scss', dest: 'assets/dev/css', linecomments: true, forcecompile: true, require: [ 'animate-sass', 'mylib' ], debugsass: true, images: '/path/to/images', relativeassets: true }, prod: { src: 'assets/scss', dest: 'assets/prod/css', outputstyle: 'compressed', linecomments: false, forcecompile: true, require: [ 'animate-sass', 'mylib' ], debugsass: false, images: '/path/to/images', relativeassets: true } }