|
| 1 | +// coffeescript-loader.mjs |
| 2 | +import { URL, pathToFileURL } from 'url'; |
| 3 | +import CoffeeScript from 'coffeescript'; |
| 4 | +import { cwd } from 'process'; |
| 5 | + |
| 6 | +const baseURL = pathToFileURL(`${cwd()}/`).href; |
| 7 | + |
| 8 | +// CoffeeScript files end in .coffee, .litcoffee or .coffee.md. |
| 9 | +const extensionsRegex = /\.coffee$|\.litcoffee$|\.coffee\.md$/; |
| 10 | + |
| 11 | +export function resolve(specifier, context, defaultResolve) { |
| 12 | + const { parentURL = baseURL } = context; |
| 13 | + // Node.js normally errors on unknown file extensions, so return a URL for |
| 14 | + // specifiers ending in the CoffeeScript file extensions. |
| 15 | + if (extensionsRegex.test(specifier)) { |
| 16 | + return { |
| 17 | + url: new URL(specifier, parentURL).href, |
| 18 | + stop: true |
| 19 | + }; |
| 20 | + } |
| 21 | + // Let Node.js handle all other specifiers. |
| 22 | + return defaultResolve(specifier, context, defaultResolve); |
| 23 | +} |
| 24 | + |
| 25 | +export function getFormat(url, context, defaultGetFormat) { |
| 26 | + // Now that we patched resolve to let CoffeeScript URLs through, we need to |
| 27 | + // tell Node.js what format such URLs should be interpreted as. For the |
| 28 | + // purposes of this loader, all CoffeeScript URLs are ES modules. |
| 29 | + if (extensionsRegex.test(url)) { |
| 30 | + return { |
| 31 | + format: 'module', |
| 32 | + stop: true |
| 33 | + }; |
| 34 | + } |
| 35 | + // Let Node.js handle all other URLs. |
| 36 | + return defaultGetFormat(url, context, defaultGetFormat); |
| 37 | +} |
| 38 | + |
| 39 | +export function transformSource(source, context, defaultTransformSource) { |
| 40 | + const { url, format } = context; |
| 41 | + |
| 42 | + if (extensionsRegex.test(url)) { |
| 43 | + return { |
| 44 | + source: CoffeeScript.compile(String(source), { bare: true }) |
| 45 | + }; |
| 46 | + } |
| 47 | + |
| 48 | + // Let Node.js handle all other sources. |
| 49 | + return defaultTransformSource(source, context, defaultTransformSource); |
| 50 | +} |
0 commit comments