This repository was archived by the owner on Aug 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathfixExportClass.js
78 lines (65 loc) · 1.88 KB
/
fixExportClass.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import * as tippex from 'tippex';
// Hack around TypeScript's broken handling of `export class` with
// ES6 modules and ES5 script target.
//
// It works because TypeScript transforms
//
// export class A {}
//
// into something like CommonJS, when we wanted ES6 modules.
//
// var A = (function () {
// function A() {
// }
// return A;
// }());
// exports.A = A;
//
// But
//
// class A {}
// export { A };
//
// is transformed into this beauty.
//
// var A = (function () {
// function A() {
// }
// return A;
// }());
// export { A };
//
// The solution is to replace the previous export syntax with the latter.
export default function fix ( code, id ) {
// Erase comments, strings etc. to avoid erroneous matches for the Regex.
const cleanCode = getErasedCode( code, id );
const re = /export\s+(default\s+)?((?:abstract\s+)?class)(?:\s+(\w+))?/g;
let match;
while ( match = re.exec( cleanCode ) ) {
// To keep source maps intact, replace non-whitespace characters with spaces.
code = erase( code, match.index, match[ 0 ].indexOf( match[ 2 ] ) );
let name = match[ 3 ];
if ( match[ 1 ] ) { // it is a default export
// TODO: support this too
if ( !name ) throw new Error( `TypeScript Plugin: cannot export an un-named class (module ${ id })` );
// Export the name ` as default`.
name += ' as default';
}
// To keep source maps intact, append the injected exports last.
code += `\nexport { ${ name } };`
}
return code;
}
function getErasedCode ( code, id ) {
try {
return tippex.erase( code );
} catch (e) {
throw new Error( `rollup-plugin-typescript: ${ e.message }; when processing: '${ id }'` );
}
}
function erase ( code, start, length ) {
const end = start + length;
return code.slice( 0, start ) +
code.slice( start, end ).replace( /[^\s]/g, ' ' ) +
code.slice( end );
}