UNPKG

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