1 | import fs from 'fs';
|
2 | import path from 'path';
|
3 | import MagicString from 'magic-string';
|
4 | import { createFilter } from 'rollup-pluginutils';
|
5 |
|
6 | var componentRegex = /@Component\({([\s\S]*)}\)$/gm;
|
7 | var templateUrlRegex = /templateUrl\s*:(.*)/g;
|
8 | var styleUrlsRegex = /styleUrls\s*:(\s*\[[\s\S]*?\])/g;
|
9 | var stringRegex = /(['"])((?:[^\\]\\\1|.)*?)\1/g;
|
10 |
|
11 | function insertText(str, dir, preprocessor) {
|
12 | if ( preprocessor === void 0 ) preprocessor = function (res) { return res; };
|
13 |
|
14 | return str.replace(stringRegex, function (match, quote, url) {
|
15 | var includePath = path.join(dir, url);
|
16 | var text = fs.readFileSync(includePath).toString();
|
17 | return '`' + preprocessor(text, includePath) + '`';
|
18 | });
|
19 | }
|
20 |
|
21 | function angular(options) {
|
22 | if ( options === void 0 ) options = {};
|
23 |
|
24 | options.preprocessors = options.preprocessors || {};
|
25 |
|
26 |
|
27 | options.exclude = options.exclude || [];
|
28 | if (typeof options.exclude === 'string' || options.exclude instanceof String) { options.exclude = [options.exclude]; }
|
29 | if (options.exclude.indexOf('node_modules/@angular/**') === -1) { options.exclude.push('node_modules/@angular/**'); }
|
30 |
|
31 | var filter = createFilter(options.include, options.exclude);
|
32 |
|
33 | return {
|
34 | name: 'angular',
|
35 | transform: function transform(source, map) {
|
36 | if (!filter(map)) { return; }
|
37 |
|
38 | var magicString = new MagicString(source);
|
39 | var dir = path.parse(map).dir;
|
40 |
|
41 | var hasReplacements = false;
|
42 | var match;
|
43 | var start, end, replacement;
|
44 |
|
45 | while ((match = componentRegex.exec(magicString)) !== null) {
|
46 | start = match.index;
|
47 | end = start + match[0].length;
|
48 |
|
49 | replacement = match[0]
|
50 | .replace(templateUrlRegex, function (match, url) {
|
51 | hasReplacements = true;
|
52 | return 'template:' + insertText(url, dir, options.preprocessors.template);
|
53 | })
|
54 | .replace(styleUrlsRegex, function (match, urls) {
|
55 | hasReplacements = true;
|
56 | return 'styles:' + insertText(urls, dir, options.preprocessors.style);
|
57 | });
|
58 |
|
59 | if (hasReplacements) { magicString.overwrite(start, end, replacement); }
|
60 | }
|
61 |
|
62 | if (!hasReplacements) { return null; }
|
63 |
|
64 | var result = { code: magicString.toString() };
|
65 | if (options.sourceMap !== false) { result.map = magicString.generateMap({ hires: true }); }
|
66 |
|
67 | return result;
|
68 | }
|
69 | };
|
70 | }
|
71 |
|
72 | export default angular;
|