You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Adonis.js 3.2如何监听视图文件变化?是否支持该功能?

Solution for Auto-Reloading Nunjucks Views in 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.js in your project
  • Update the cache option 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:

  1. Install nodemon as a dev dependency:
    npm install nodemon --save-dev
    
  2. 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,njk tells nodemon to watch for changes in JavaScript and Nunjucks files
    • --watch flags specify directories to monitor
    • Now run npm run dev instead of adonis 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:24:57