Grunt
grunt-contrib-connect
grunt-contrib-less
grunt-contrib-watch
Node.js
开始做点功能吧:Grunt实现Less实时编译,web服务器。实现这些功能,主要的就是安装Grunt插件、编写配置文件的工作。安装很简单。主要讲解这个配置文件吧。
Gruntfile.js文件:module.exports = function(grunt) { // include connect-include var ssInclude = require('connect-include'); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), less: { development: { files: [{ expand: true, cwd: './static/less', src: ['**/*.less'], dest: 'static/css', ext: '.css' }] } }, watch: { options: { livereload: true }, scripts: { files: ['./static/less/**/*.less'], tasks: ['less'], options: { spawn: false, }, }, }, connect: { server: { options: { port: 8080, // 在connect与watch同时运行的时候,keepalive不能为true,这里注释了keepalive,因为他的默认值就是false。 // keepalive: true, // livereload: true, base: './static', middleware: function(connect, options) { // Same as in grunt-contrib-connect var middlewares = []; var directory = options.directory || options.base[options.base.length - 1]; if (!Array.isArray(options.base)) { options.base = [options.base]; } // Here we insert connect-include, use the same pattern to add other middleware middlewares.push(ssInclude(directory)); // Same as in grunt-contrib-connect options.base.forEach(function(base) { middlewares.push(connect.static(base)); }); middlewares.push(connect.directory(directory)); return middlewares; } } } } }); // Load the plugin that provides the 'uglify' task. // grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-contrib-watch'); // Default task(s). // grunt.registerTask('default', ['uglify']); grunt.registerTask('default', [ 'connect','watch']); //使用watch,实时编译less成功 };
package.json文件:{ 'name': 'Grunt-base', 'version': '0.0.0', 'description': '', 'main': 'index.js', 'scripts': { 'test': 'echo \'Error: no test specified\' && exit 1' }, 'author': '', 'license': 'ISC', 'devDependencies': { 'grunt': '^0.4.5', 'grunt-contrib-connect': '^0.9.0', 'grunt-contrib-less': '^1.0.0', 'grunt-contrib-watch': '^0.6.1' }, 'dependencies': { 'connect-include': '^0.2.1' }}
插件安装完成,写好项目配置文件,运行:使用CMD命令行:grunt
浏览器访问http://127.0.0.1:8080/ 查看效果:
我的项目结构:
注意事项:如果你在使用中,grunt-contrib-connect、grunt-contrib-watch两个同时搭配使用,出现不能正常工作的问题,要注意这个connect的这个配置:keepalive: false。如果没有配合grunt-contrib-watch的时候,keepalive配置往往是true,配合watch监听的话,这个值就是false。
依赖Node.js环境