首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Grunt LiveReload 實現頁面自動刷新的兩種方案詳解

     編輯:PHP 綜合知識

方案對比

方案優點缺點
A: grunt-contrib-watch + 瀏覽器插件配置極簡、無需本地服務器改動需安裝 Chrome/Firefox 插件、不支持 IE
B: grunt-contrib-watch + grunt-contrib-connect + connect-livereload內建靜態服務器、無插件依賴、自動注入脚本配置稍繁瑣、需關閉瀏覽器插件

方案 A:瀏覽器插件模式

1. 安裝依賴

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

2. 安裝瀏覽器擴展

3. 本地靜態服務器

需自行搭建 Apache/Nginx/IIS,或使用 python -m http.server 8000 臨時啟動。不能直接打開 file:// 協議文件,LiveReload 需 HTTP 環境。

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 // 默認端口 35729
                }
            }
        }
    });
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.registerTask('live', ['watch']);
};

5. 運行與使用

grunt live
# 輸出: Waiting...
# 瀏覽器打開 https://localhost/your-project/
# 點擊 LiveReload 圖標,中心變實心 → 啟用成功
# 修改任意文件 → 瀏覽器自動刷新

方案 B:內建服務器無插件模式

1. 安裝依賴

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

2. Gruntfile.js(完整配置)

module.exports = function(grunt) {
    const lrPort = 35729;
    const lrSnippet = require('connect-livereload')({ port: lrPort });

    const lrMiddleware = function(connect, options) {
        return [
            lrSnippet,                    // 注入 livereload.js
            connect.static(options.base[0]), // 靜態文件服務
            connect.directory(options.base[0]) // 目錄瀏覽
        ];
    };

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        connect: {
            options: {
                port: 8000,
                hostname: 'localhost',
                base: '.' // 項目根目錄
            },
            livereload: {
                options: {
                    middleware: lrMiddleware
                }
            }
        },
        watch: {
            client: {
                files: ['*.html', 'css/**/*', 'js/**/*', 'images/**/*'],
                options: {
                    livereload: lrPort // 關鍵:指定端口,watch 內建 livereload 服務
                }
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-connect');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.registerTask('live', ['connect:livereload', 'watch']);
};

3. 運行

grunt live
# 輸出:
# Running "connect:livereload" (connect) task
# Started connect web server on https://127.0.0.1:8000
# Running "watch" task
# Waiting...
# 瀏覽器打開 https://127.0.0.1:8000/ 即可自動刷新,無需任何插件

常見問題

  • CSS 不刷新:確保 files 匹配模式包含 css/**/*;
  • 端口衝突:修改 lrPort 和 connect.options.port;
  • 修改文件無反應:檢查 grunt watch 是否輸出 File "xxx.css" changed,否則 glob 模式錯誤;
  • 方案 B 下已安裝瀏覽器插件:必須禁用插件,否則雙重注入導致錯誤。

進階:配合 Sass/Less/TypeScript 編譯

watch: {
    sass: {
        files: ['scss/**/*.scss'],
        tasks: ['sass:dev'], // 先編譯
        options: { livereload: lrPort }
    },
    ts: {
        files: ['ts/**/*.ts'],
        tasks: ['typescript:dev'],
        options: { livereload: lrPort }
    },
    livereload: { // 專門監聽編譯產出
        files: ['css/**/*.css', 'js/**/*.js'],
        options: { livereload: lrPort }
    }
}

總結

方案 A 適合已有成熟後端環境、團隊統一使用 Chrome 的項目;方案 B 適合純前端項目、快速原型、無插件限制的場景。現代構建工具(Vite, Webpack Dev Server, Snowpack)已內建 HMR(熱模塊替換),比 LiveReload 更強大,新項目建議直接使用新一代工具鏈。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved