UNPKG

2.19 kBJavaScriptView Raw
1const Asset = require('../Asset');
2const localRequire = require('../utils/localRequire');
3const isAccessedVarChanged = require('../utils/isAccessedVarChanged');
4
5class TypeScriptAsset extends Asset {
6 constructor(name, options) {
7 super(name, options);
8 this.type = 'js';
9 this.cacheData.env = {};
10 }
11
12 shouldInvalidate(cacheData) {
13 return isAccessedVarChanged(cacheData);
14 }
15
16 async generate() {
17 // require typescript, installed locally in the app
18 let typescript = await localRequire('typescript', this.name);
19 let transpilerOptions = {
20 compilerOptions: {
21 module: this.options.scopeHoist
22 ? typescript.ModuleKind.ESNext
23 : typescript.ModuleKind.CommonJS,
24 jsx: typescript.JsxEmit.Preserve,
25
26 // it brings the generated output from TypeScript closer to that generated by Babel
27 // see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html
28 esModuleInterop: true
29 },
30 fileName: this.relativeName
31 };
32
33 let tsconfig = await this.getConfig(['tsconfig.json']);
34
35 // Overwrite default if config is found
36 if (tsconfig) {
37 transpilerOptions.compilerOptions = Object.assign(
38 transpilerOptions.compilerOptions,
39 tsconfig.compilerOptions
40 );
41 }
42 transpilerOptions.compilerOptions.noEmit = false;
43 transpilerOptions.compilerOptions.sourceMap = this.options.sourceMaps;
44
45 // Transpile Module using TypeScript and parse result as ast format through babylon
46 let transpiled = typescript.transpileModule(
47 this.contents,
48 transpilerOptions
49 );
50 let sourceMap = transpiled.sourceMapText;
51
52 if (sourceMap) {
53 sourceMap = JSON.parse(sourceMap);
54 sourceMap.sources = [this.relativeName];
55 sourceMap.sourcesContent = [this.contents];
56
57 // Remove the source map URL
58 let content = transpiled.outputText;
59 transpiled.outputText = content.substring(
60 0,
61 content.lastIndexOf('//# sourceMappingURL')
62 );
63 }
64
65 return [
66 {
67 type: 'js',
68 value: transpiled.outputText,
69 map: sourceMap
70 }
71 ];
72 }
73}
74
75module.exports = TypeScriptAsset;