使用Browsersync API时子目录文件更新不触发浏览器刷新
Got it, let's break down why your Browsersync setup isn't picking up changes in your target subdirectories and get it working properly.
The Core Issue
Right now, your Browsersync config only calls bs.reload("*.html") once on startup, and it doesn't have explicit watch rules set up to monitor changes across all files in the target directory (including subdirectories). Browsersync won't automatically watch all files unless you explicitly tell it to.
Step-by-Step Solutions
1. Add Explicit Watch Rules to Browsersync
Update your Browsersync init config to include a files array that targets all relevant files in target and its subdirectories. The ** glob pattern will match any nested subdirectory:
var bs = require("browser-sync").create(); // 启动Browsersync服务器并配置监听规则 bs.init({ server: './target', // 开启自动监听模式 watch: true, // 指定要监听的文件类型(覆盖所有子目录) files: [ 'target/**/*.html', 'target/**/*.css', 'target/**/*.js' // 可根据项目需求添加其他文件类型,比如图片、字体等 ] });
2. Ensure PostCSS Triggers Reload After Compilation
If your CLI tool compiles CSS asynchronously, you'll want to trigger a Browsersync reload after the compiled CSS file has been written to the target directory. This ensures Browsersync picks up the fresh changes immediately.
For example, if you're using PostCSS programmatically, add a reload call in your compilation callback:
// 示例PostCSS编译逻辑 const postcss = require('postcss'); const fs = require('fs'); postcss([/* 这里放入你的PostCSS插件,比如autoprefixer、cssnano等 */]) .process(fs.readFileSync('src/main/css/main.css', 'utf8'), { from: 'src/main/css/main.css', to: 'target/css/main.compiled.css' }) .then(result => { fs.writeFileSync('target/css/main.compiled.css', result.css); // 编译完成后触发Browsersync全页面刷新 bs.reload(); });
3. Verify File Write Paths
Double-check that your CLI tool is writing compiled files to the correct target subdirectories. If the files aren't actually being updated in target (e.g., a typo in the output path), Browsersync will have no changes to detect.
Final Notes
With these adjustments, Browsersync will actively watch all specified files in target and its subdirectories. Any change—whether from your CSS compilation or manual edits to HTML/JS files—will trigger an automatic browser refresh.
内容的提问来源于stack exchange,提问作者Ole

