Adonis.js 3.2如何监听视图文件变化?是否支持该功能?
Hey there! I totally get the frustration of having to restart your server every time you tweak a Nunjucks template in Adonis.js 3.2. Let’s break down how to fix this—there are a couple of approaches depending on what you need:
1. Disable View Cache (No Server Restart Needed!)
The simplest fix for view changes is to turn off Nunjucks template caching in development mode. Adonis.js lets you control this via the view config:
- Open
config/views.jsin your project - Update the
cacheoption to disable caching when in development:module.exports = { engine: 'nunjucks', cache: process.env.NODE_ENV !== 'development' // Cache only in production }
With this setting, any changes to your .njk files will be picked up immediately when you refresh your browser—no server restart required. This is the most efficient approach for view tweaks.
2. Extend Server Watch to Include View Files
If you also need the server to restart for other file types (or if disabling cache isn’t enough for your workflow), you can modify Adonis’s built-in file watcher to monitor Nunjucks templates:
Option A: Modify the Serve Command
Update your package.json scripts to specify additional files to watch when running adonis serve:
"scripts": { "serve": "adonis serve --watch resources/views/**/*.njk,app/**/*.js,config/**/*.js" }
The --watch flag lets you list specific files or directories (using glob patterns) that trigger a server restart when changed.
Option B: Use Nodemon for More Flexibility
For even more control, swap Adonis’s built-in watcher with nodemon, a popular tool for auto-reloading Node.js apps:
- Install nodemon as a dev dependency:
npm install nodemon --save-dev - Add a new dev script to
package.json:"scripts": { "dev": "nodemon --watch app --watch config --watch resources/views -e js,njk --exec adonis serve" }-e js,njktells nodemon to watch for changes in JavaScript and Nunjucks files--watchflags specify directories to monitor- Now run
npm run devinstead ofadonis serve—any changes to your views or JS files will trigger an automatic server restart.
Quick Note on Adonis 3.2 Default Behavior
Just to clarify: Adonis.js 3.2’s default file watcher only monitors JavaScript (.js) and JSON (.json) files out of the box. View templates (like Nunjucks .njk files) aren’t included in this default set, which is why you’ve had to restart manually. The fixes above address this by either disabling view caching (for instant browser refreshes) or extending the watcher to include template files.
内容的提问来源于stack exchange,提问作者Goper Leo Zosa

