方案一:grunt-livereload + Chrome Plug-in
優點:安裝、配置簡單方便。
缺點:需要配合指定的瀏覽器插件(Firefox也有相關插件,IE么你懂的)。
1. 需要安裝2個插接件:grunt-contrib-watch、connect-livereload
執行命令:
代碼如下:
npm install --save-dev grunt-contrib-watch connect-livereload
2. 安裝瀏覽器插件:Chrome LiveReload
3. 配置一個Web服務器(IIS/Apache),LiveReload需要在本地服務器環境下運行(對file:///文件路徑支持并不是很好)。
4. 修改Gruntfile.js文件:
module.exports = function(grunt) {
// 項目配置(任務配置)
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
client: {
files: ['*.html', 'css/*', 'js/*', 'images/**/*'],
options: {
livereload: true
}
}
}
});
// 加載插件
grunt.loadNpmTasks('grunt-contrib-watch');
// 自定義任務
grunt.registerTask('live', ['watch']);
};
5. 執行:grunt live
看到如下提示,說明已經開始監聽任務:
代碼如下:
Running "watch" task
Waiting...
6. 打開我們的頁面,例如:http://localhost/
7. 再點擊Chrome LiveReload插件的ICON,此時ICON圓圈中心的小圓點變成實心的,說明插件執行成功。此時你改下網站文件看看,是不是實時更新了?
方案二:grunt-contrib-watch + grunt-contrib-connect + grunt-livereload
優點:自動搭建靜態文件服務器,不需在自己電腦上搭建Web服務器。
不需要瀏覽器插件的支持(不現定于某個瀏覽器)。
不需要給網頁手動添加livereload.js。
缺點:對于剛接觸的人,配置略顯復雜。
1. 安裝我們所需要的3個插件:grunt-contrib-watch、grunt-contrib-connect、connect-livereload
執行命令:
代碼如下:
npm install --save-dev grunt-contrib-watch grunt-contrib-connect connect-livereload
2. 修改Gruntfile.js文件:
module.exports = function(grunt) {
// LiveReload的默認端口號,你也可以改成你想要的端口號
var lrPort = 35729;
// 使用connect-livereload模塊,生成一個與LiveReload腳本
// <script src="http://127.0.0.1:35729/livereload.js?snipver=1" type="text/javascript"></script>
var lrSnippet = require('connect-livereload')({ port: lrPort });
// 使用 middleware(中間件),就必須關閉 LiveReload 的瀏覽器插件
var lrMiddleware = function(connect, options) {
return [
// 把腳本,注入到靜態文件中
lrSnippet,
// 靜態文件服務器的路徑
connect.static(options.base[0]),
// 啟用目錄瀏覽(相當于IIS中的目錄瀏覽)
connect.directory(options.base[0])
];
};
// 項目配置(任務配置)
grunt.initConfig({
// 讀取我們的項目配置并存儲到pkg屬性中
pkg: grunt.file.readJSON('package.json'),
// 通過connect任務,創建一個靜態服務器
connect: {
options: {
// 服務器端口號
port: 8000,
// 服務器地址(可以使用主機名localhost,也能使用IP)
hostname: 'localhost',
// 物理路徑(默認為. 即根目錄) 注:使用'.'或'..'為路徑的時,可能會返回403 Forbidden. 此時將該值改為相對路徑 如:/grunt/reloard。
base: '.'
},
livereload: {
options: {
// 通過LiveReload腳本,讓頁面重新加載。
middleware: lrMiddleware
}
}
},
// 通過watch任務,來監聽文件是否有更改
watch: {
client: {
// 我們不需要配置額外的任務,watch任務已經內建LiveReload瀏覽器刷新的代碼片段。
options: {
livereload: lrPort
},
// '**' 表示包含所有的子目錄
// '*' 表示包含所有的文件
files: ['*.html', 'css/*', 'js/*', 'images/**/*']
}
}
}); // grunt.initConfig配置完畢
// 加載插件
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-watch');
// 自定義任務
grunt.registerTask('live', ['connect', 'watch']);
};
5. 執行:grunt live
看到如下提示,說明Web服務器搭建完成,并且開始監聽任務:
代碼如下:
Running "connect:livereload" (connect) task
Started connect web server on 127.0.0.1:8000.
Running "watch" task
Waiting...
注:執行該命令前,如果你有安裝過LiveReload的瀏覽器插件,必須關閉。
6. 打開我們的頁面,例如:http://localhost:8000/ 或 http://127.0.0.1:8000/
注:這里所打開的本地服務器地址,是我們剛才通過connect所搭建的靜態文件服務器地址,而不是之前你用IIS或Apache自己搭建Web服務器地址。
以上就是本文詳解Grunt插件之LiveReload實現頁面自動刷新(兩種方案),希望大家喜歡。
新聞熱點
疑難解答