UNPKG

1.45 kBJavaScriptView Raw
1/* eslint node/no-deprecated-api: [error, {ignoreGlobalItems: ["require.extensions"]}] */
2
3"use strict";
4
5const path = require("path");
6const espowerSource = require("espower-source");
7const minimatch = require("minimatch");
8const sourceMapSupport = require("source-map-support");
9const tsNodeRegister = require("ts-node").register;
10const sourceCache = {};
11
12function espowerTypeScript(options, tsNodeOptions) {
13 tsNodeRegister(tsNodeOptions);
14
15 // install source-map-support again to correct the source-map
16 sourceMapSupport.install({
17 environment: "node",
18 retrieveFile: (path) => sourceCache[path],
19 });
20
21 const { extensions = ["ts", "tsx"] } = options;
22 extensions.forEach((ext) => {
23 espowerTsRegister(`.${ext}`, options);
24 });
25}
26
27function espowerTsRegister(ext, options) {
28 const cwd = options.cwd || process.cwd();
29 const pattern = path.join(cwd, options.pattern);
30
31 const originalExtension = require.extensions[ext];
32 require.extensions[ext] = (module, filepath) => {
33 if (!minimatch(filepath, pattern)) {
34 return originalExtension(module, filepath);
35 }
36 const originalCompile = module._compile;
37 module._compile = function (code, filepath) {
38 const newSource = espowerSource(code, filepath, options);
39 sourceCache[filepath] = newSource;
40 return originalCompile.call(this, newSource, filepath);
41 };
42 return originalExtension(module, filepath);
43 };
44}
45
46module.exports = espowerTypeScript;