1 |
|
2 |
|
3 | "use strict";
|
4 |
|
5 | const path = require("path");
|
6 | const espowerSource = require("espower-source");
|
7 | const minimatch = require("minimatch");
|
8 | const sourceMapSupport = require("source-map-support");
|
9 | const tsNodeRegister = require("ts-node").register;
|
10 | const sourceCache = {};
|
11 |
|
12 | function espowerTypeScript(options, tsNodeOptions) {
|
13 | tsNodeRegister(tsNodeOptions);
|
14 |
|
15 |
|
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 |
|
27 | function 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 |
|
46 | module.exports = espowerTypeScript;
|