grunt-contrib-connect自动刷新html页面

时间:2023-03-09 17:38:03
grunt-contrib-connect自动刷新html页面

grunt-contrib-connect可以在我们开发的时候自动刷新页面,省去了手动刷新的时间。

下面说一下如何配置grunt-contrib-connect

1、下载插件包

npm install grunt-contrib-connect --save-dev

2、在gruntfile.js中引入包

grunt.loadNpmTasks('grunt-contrib-connect');

3、配置connec任务

// The actual grunt server settings
connect: {
options: {
port: 9000, //服务器的端口号,可用localhost:9000访问
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost', //服务器域名
livereload: 35729 //声明给watch监听的端口 },
livereload: {
options: {
open: true, //true:一直打开链接,不然浏览器只打开一次
middleware: function (connect) { //设置服务器中间件,主要用于获取静态文件,不设置中间件,node服务器是没有输出的,和php或java服务器不同
return [ //不懂中间件的可以去看下node.js
serveStatic('.tmp'), //获取tmp目录下的文件
connect().use(
'/bower_components', //设置挂载,如果路径中有/bower_components则会执行这个中间件
serveStatic('./bower_components') //获取bower_components下的文件,主要是bower安装的包 ),
serveStatic('public') //获取public目录下的文件,
]; //这3个中间件主要是从服务器获取展示html要用的东西,比如html文件,js,css,图片等
}
}
}
},

注意在较高版本的grunt-contrib-connect中已经不支持connect.static,需要使用serve-static

4、安装serve-static

cnpm install serve-static --save

在gruntfile.js中引入文件,这个serveStatic就是步骤3中的变量。

module.exports = function(grunt) {
var serveStatic = require('serve-static');
// Project configuration.
grunt.initConfig({

5、用watch监视端口

watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib_test: {
files: '<%= jshint.lib_test.src %>',
tasks: ['jshint:lib_test', 'qunit']
},
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
livereload: { //监听connect端口
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'public/**/*.html', //html
'public/**/*.css' //css
]
}
}

我这里只设置了public下的html和css变动会通知端口刷新页面

6、设置默认启动任务

grunt.registerTask('default', ['jshint','concat', 'uglify','wiredep', 'connect','watch']);

7、输入命令运行grunt

grunt

这时你的默认浏览器会打开一个标签,显示你设置的.html文件,更改html或css浏览器会自动刷新。