之前抽时间研究了下gruntjs,分享一下使用grunt编译sass源文件的方案。gruntjs作为nodejs的自动化工具,现在有大量可用插件可让你的工具效率提升,有兴趣的可以了解下。http://gruntjs.com/
1. 创建项目目录,进到目录。
mkdir grunt3
cd grunt3
2. 创建项目包管理文件 package.json
1 2 3 4 5 6 7 8 9 10 11 12 | { "name" : "myproject" , "description" : "我的grunt项目" , "version" : "0.1.0" , "readmeFilename" : "README.md" , "devDependencies" : { "grunt" : "~0.4.1" , "grunt-contrib-sass" : "~0.3.0" , "grunt-contrib-watch" : "~0.4.4" , "grunt-contrib-cssmin" : "~0.6.1" } } |
3. 安装grunt包及需要用到的组件包
npm install -g grunt-cli
npm install grunt grunt-contrib-sass grunt-contrib-cssmin grunt-contrib-watch --save-dev
4. 创建grunt任务文件 Gruntfile.coffee
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | module.exports = (grunt)-> grunt.initConfig pkg: grunt.file.readJSON( 'package.json' ) sass: dist: options: style: 'compact' files: 'css/style.css' : 'sass/style.sass' dev: options: style: 'expanded' cssmin: min: files: 'css/style.min.css' : 'css/style.css' watch: css: files: [ 'sass/_common.sass' , 'sass/style.sass' ] tasks: [ 'sass:dist' , 'cssmin:min' ] grunt.loadNpmTasks( 'grunt-contrib-sass' ) grunt.loadNpmTasks( 'grunt-contrib-cssmin' ) grunt.loadNpmTasks( 'grunt-contrib-watch' ) # Default task(s) grunt.registerTask( 'default' , [ 'sass' ]) undefined |
上面的配置中,将sass文件放在sass目录下,css文件放在css目录下。style.sass中包含_common.sass文件,当两个中的一个发生修改时,重新编译style.sass文件。编译后执行cssmin压缩css文件。
5. 使用
创建css sass目录,在sass目录中创建sass源文件,终端中输入 grunt watch。修改sass源文件时,grunt会自动执行编译。
相关链接:
gruntjs: http://gruntjs.com/
grunt-contrib-watch: https://github.com/gruntjs/grunt-contrib-watch
grunt-contrib-cssmin: https://github.com/gruntjs/grunt-contrib-cssmin
grunt-contrib-sass https://github.com/gruntjs/grunt-contrib-sass
grunt插件列表: https://github.com/gruntjs