1 | const Asset = require('../Asset');
|
2 | const localRequire = require('../utils/localRequire');
|
3 | const isAccessedVarChanged = require('../utils/isAccessedVarChanged');
|
4 |
|
5 | class 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 |
|
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 |
|
27 |
|
28 | esModuleInterop: true
|
29 | },
|
30 | fileName: this.relativeName
|
31 | };
|
32 |
|
33 | let tsconfig = await this.getConfig(['tsconfig.json']);
|
34 |
|
35 |
|
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 |
|
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 |
|
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 |
|
75 | module.exports = TypeScriptAsset;
|