运行钩子


# 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() 

为运行该示例,请添加一个 package.json 文件,其中包含 CoffeeScript 文件的模块类型。

{
  "type": "module"
} 

这仅用于运行示例。在实际应用中,加载器中的 getPackageType() 必须 能够返回 Node.js 已知的 format,即使 package.json 中没有 显式指定类型,否则 nextLoad 调用会抛出 ERR_UNKNOWN_FILE_EXTENSION (若为 undefined)或 ERR_UNKNOWN_MODULE_FORMAT(若它不是已知的 加载钩子 文档中列出的格式)。

使用上述钩子模块,运行 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 文件, 也是如此。