forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
89 lines (76 loc) · 2.72 KB
/
index.ts
File metadata and controls
89 lines (76 loc) · 2.72 KB
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
79
80
81
82
83
84
85
86
87
88
89
/* eslint-disable */
import Transpiler from '../';
import { LoaderContext } from '../../transpiled-module';
// using: regex, capture groups, and capture group variables.
const templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*([,}]))/gm;
const stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
const stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
function replaceStringsWithRequires(string, extensionConfig, addDependency) {
return string.replace(stringRegex, (match, quote, url) => {
if (url.charAt(0) !== '.') {
// eslint-disable-next-line
url = './' + url;
}
const urlParts = url.split('.');
const extension = urlParts[urlParts.length - 1];
const transpilers = extensionConfig[extension] || [];
const finalUrl = `!raw-loader!${transpilers
.map(t => t.transpiler.name)
.join('!')}!${url}`;
addDependency(finalUrl, { isAbsolute: false });
return "require('" + finalUrl + "')";
});
}
/**
* Converts Angular statements to css/html to require statements. Taken from
* https://github.com/TheLarkInn/angular2-template-loader/blob/master/index.js
*
* @class Angular2Transpiler
* @extends {Transpiler}
*/
class Angular2Transpiler extends Transpiler {
constructor() {
super('binary-loader');
}
doTranspilation(code: string, loaderContext: LoaderContext) {
const styleProperty = 'styles';
const templateProperty = 'template';
const newSource = code
.replace(templateUrlRegex, (match, url) => {
// replace: templateUrl: './path/to/template.html'
// with: template: require('./path/to/template.html')
// or: templateUrl: require('./path/to/template.html')
// if `keepUrl` query parameter is set to true.
return (
templateProperty +
':' +
replaceStringsWithRequires(
url,
loaderContext.options.preTranspilers,
loaderContext.addDependency
)
);
})
.replace(stylesRegex, (match, urls) => {
// replace: stylesUrl: ['./foo.css', "./baz.css", "./index.component.css"]
// with: styles: [require('./foo.css'), require("./baz.css"), require("./index.component.css")]
// or: styleUrls: [require('./foo.css'), require("./baz.css"), require("./index.component.css")]
// if `keepUrl` query parameter is set to true.
return (
styleProperty +
':' +
replaceStringsWithRequires(
urls,
loaderContext.options.preTranspilers,
loaderContext.addDependency
)
);
});
return Promise.resolve({
transpiledCode: newSource,
});
}
}
const transpiler = new Angular2Transpiler();
export { Angular2Transpiler };
export default transpiler;