| 方案 | 優點 | 缺點 |
|---|---|---|
| A: grunt-contrib-watch + 瀏覽器插件 | 配置極簡、無需本地服務器改動 | 需安裝 Chrome/Firefox 插件、不支持 IE |
| B: grunt-contrib-watch + grunt-contrib-connect + connect-livereload | 內建靜態服務器、無插件依賴、自動注入脚本 | 配置稍繁瑣、需關閉瀏覽器插件 |
npm install --save-dev grunt-contrib-watch connect-livereload
需自行搭建 Apache/Nginx/IIS,或使用 python -m http.server 8000 臨時啟動。不能直接打開 file:// 協議文件,LiveReload 需 HTTP 環境。
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']);
};
grunt live # 輸出: Waiting... # 瀏覽器打開 https://localhost/your-project/ # 點擊 LiveReload 圖標,中心變實心 → 啟用成功 # 修改任意文件 → 瀏覽器自動刷新
npm install --save-dev grunt-contrib-watch grunt-contrib-connect connect-livereload
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']);
};
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/ 即可自動刷新,無需任何插件
files 匹配模式包含 css/**/*;lrPort 和 connect.options.port;grunt watch 是否輸出 File "xxx.css" changed,否則 glob 模式錯誤;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 更強大,新項目建議直接使用新一代工具鏈。