- node-hmrは、require関数により読み込まれたモジュール(=require.cacheに追加されているモジュール)のみ監視する
- require関数でエラーが発生すると、node-hmrはそのモジュールの監視を停止する
- require関数で発生したエラーをキャッチしたときに、
require.cache[moduleId] = { id: moduleId }
を追加することで監視を継続できる - 代替モジュール: error-handled-node-hmr
test.js
:
const path = require('path')
const hmr = require('node-hmr')
var watchDir = './'
var handleFile = './handle.js'
hmr(() => {
try {
require(handleFile)
} catch (e) {
console.error(e)
const moduleId = path.resolve(watchDir, handleFile)
require.cache[moduleId] = { id: moduleId }
}
console.log('handle!')
}, { watchDir: watchDir, watchFilePatterns: [handleFile] })
handle.js
:
\
console:
handle.js:1
\
^
SyntaxError: Invalid or unexpected token
at wrapSafe (node:internal/modules/cjs/loader:1024:16)
at Module._compile (node:internal/modules/cjs/loader:1072:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at HMR.hmr.watchDir [as callback] (test.js:9:5)
at HMR.init (node-hmr@1.3.1\node_modules\node-hmr\index.js:74:10)
at Object.<anonymous> (test.js:5:1)
handle!
エラーをキャッチしたあと、ファイルを変更するとhandle!
とメッセージが表示される。