|
| 1 | +/* tslint:disable:no-eval */ |
| 2 | + |
| 3 | +import {dirname, join} from 'path'; |
| 4 | +import {readFileSync, writeFileSync} from 'fs'; |
| 5 | +import {sync as glob} from 'glob'; |
| 6 | + |
| 7 | +/** Finds all JavaScript files in a directory and inlines all resources of Angular components. */ |
| 8 | +export function inlineResourcesForDirectory(folderPath: string) { |
| 9 | + glob(join(folderPath, '**/*.js')).forEach(filePath => inlineResources(filePath)); |
| 10 | +} |
| 11 | + |
| 12 | +/** Inlines the external resources of Angular components of a file. */ |
| 13 | +export function inlineResources(filePath: string) { |
| 14 | + let fileContent = readFileSync(filePath, 'utf-8'); |
| 15 | + |
| 16 | + fileContent = inlineTemplate(fileContent, filePath); |
| 17 | + fileContent = inlineStyles(fileContent, filePath); |
| 18 | + fileContent = removeModuleId(fileContent); |
| 19 | + |
| 20 | + writeFileSync(filePath, fileContent, 'utf-8'); |
| 21 | +} |
| 22 | + |
| 23 | +/** Inlines the templates of Angular components for a specified source file. */ |
| 24 | +function inlineTemplate(fileContent: string, filePath: string) { |
| 25 | + return fileContent.replace(/templateUrl:\s*'([^']+?\.html)'/g, (match, templateUrl) => { |
| 26 | + const templatePath = join(dirname(filePath), templateUrl); |
| 27 | + const templateContent = loadResourceFile(templatePath); |
| 28 | + return `template: "${templateContent}"`; |
| 29 | + }); |
| 30 | +} |
| 31 | + |
| 32 | +/** Inlines the external styles of Angular components for a specified source file. */ |
| 33 | +function inlineStyles(fileContent: string, filePath: string) { |
| 34 | + return fileContent.replace(/styleUrls:\s*(\[[\s\S]*?])/gm, (match, styleUrlsValue) => { |
| 35 | + // The RegExp matches the array of external style files. This is a string right now and |
| 36 | + // can to be parsed using the `eval` method. The value looks like "['AAA.css', 'BBB.css']" |
| 37 | + const styleUrls = eval(styleUrlsValue) as string[]; |
| 38 | + |
| 39 | + const styleContents = styleUrls |
| 40 | + .map(url => join(dirname(filePath), url)) |
| 41 | + .map(path => loadResourceFile(path)); |
| 42 | + |
| 43 | + return `styles: ["${styleContents.join(',')}"]`; |
| 44 | + }); |
| 45 | +} |
| 46 | + |
| 47 | +/** Remove every mention of `moduleId: module.id` */ |
| 48 | +function removeModuleId(fileContent: string) { |
| 49 | + return fileContent.replace(/\s*moduleId:\s*module\.id\s*,?\s*/gm, ''); |
| 50 | +} |
| 51 | + |
| 52 | +/** Loads the specified resource file and drops line-breaks of the content. */ |
| 53 | +function loadResourceFile(filePath: string): string { |
| 54 | + return readFileSync(filePath, 'utf-8') |
| 55 | + .replace(/([\n\r]\s*)+/gm, ' ') |
| 56 | + .replace(/"/g, '\\"'); |
| 57 | +} |
0 commit comments