UNPKG

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