正在运行的钩子
¥Running hooks
# main.coffee
import { scream } from './scream.coffee'
console.log scream 'hello, world'
import { version } from 'node:process'
console.log "Brought to you by Node.js version #{version}"
# scream.coffee
export scream = (str) -> str.toUpperCase()
为了运行示例,添加一个包含 CoffeeScript 文件的模块类型的 package.json
文件。
¥For the sake of running the example, add a package.json
file containing the
module type of the CoffeeScript files.
{
"type": "module"
}
这仅用于运行示例。在现实世界的加载器中,getPackageType()
必须能够返回 Node.js 已知的 format
,即使在 package.json
中没有明确的类型,否则 nextLoad
调用将抛出 ERR_UNKNOWN_FILE_EXTENSION
(如果未定义)或 ERR_UNKNOWN_MODULE_FORMAT
(如果它不是 加载钩子 文档中列出的已知格式)。
¥This is only for running the example. In real world loaders, getPackageType()
must be
able to return an format
known to Node.js even in the absence of an explicit type in a
package.json
, or otherwise the nextLoad
call would throw ERR_UNKNOWN_FILE_EXTENSION
(if undefined) or ERR_UNKNOWN_MODULE_FORMAT
(if it's not a known format listed in
the load hook documentation).
使用前面的钩子模块,运行 node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
或 node --import ./coffeescript-sync-hooks.mjs ./main.coffee
会导致 main.coffee
在其源代码从磁盘加载之后但在 Node.js 执行它之前转换为 JavaScript;对于通过任何加载文件的 import
语句引用的任何 .coffee
、.litcoffee
或 .coffee.md
文件,依此类推。
¥With the preceding hooks modules, running
node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee
or node --import ./coffeescript-sync-hooks.mjs ./main.coffee
causes main.coffee
to be turned into JavaScript after its source code is
loaded from disk but before Node.js executes it; and so on for any .coffee
,
.litcoffee
or .coffee.md
files referenced via import
statements of any
loaded file.