UNPKG

1.3 kBJavaScriptView Raw
1const loaderUtils = require("loader-utils");
2const ts = require("typescript");
3const path = require("path");
4const fs = require("fs-extra");
5
6function loader(content) {
7 if (this.cacheable) {
8 this.cacheable();
9 }
10
11 const options = loaderUtils.getOptions(this) || {};
12
13 const resourcePath = this.resourcePath.replace(/\\/g, "/");
14
15 const resourceDirPath = path.dirname(resourcePath);
16 const configPath = options.tsConfigPath || ts.findConfigFile(resourceDirPath, ts.sys.fileExists, "tsconfig.json");
17 const contextPath = path.dirname(configPath).replace(/\\/g, "/");
18
19 const parsedConfig = ts.parseJsonConfigFileContent(fs.readJsonSync(configPath), ts.sys, path.dirname(configPath));
20 parsedConfig.options.outDir = parsedConfig.options.outDir || path.resolve(path.dirname(configPath), "dist");
21
22 const result = ts.transpileModule(content, {
23 compilerOptions: parsedConfig.options,
24 reportDiagnostics: false
25 });
26
27 const sourceMap = JSON.parse(result.sourceMapText);
28 const fileRelativePath = path.relative(contextPath, resourcePath);
29 sourceMap.sources = [fileRelativePath];
30 sourceMap.file = fileRelativePath;
31 sourceMap.sourcesContent = [content];
32
33 this.callback(undefined, result.outputText, sourceMap);
34}
35
36module.exports = loader;
\No newline at end of file