MCPcopy
hub / github.com/angular/angular-cli / addSnippet

Function addSnippet

packages/schematics/angular/web-worker/index.ts:31–75  ·  view source on GitHub ↗
(options: WebWorkerOptions)

Source from the content-addressed store, hash-verified

29import { Schema as WebWorkerOptions } from './schema';
30
31function addSnippet(options: WebWorkerOptions): Rule {
32 return (host: Tree, context: SchematicContext) => {
33 context.logger.debug('Updating appmodule');
34
35 if (options.path === undefined) {
36 return;
37 }
38
39 const fileRegExp = new RegExp(`^${options.name}.*\\.ts`);
40 const siblingModules = host
41 .getDir(options.path)
42 .subfiles // Find all files that start with the same name, are ts files,
43 // and aren't spec or module files.
44 .filter((f) => fileRegExp.test(f) && !/(module|spec|config|routes)\.ts$/.test(f))
45 // Sort alphabetically for consistency.
46 .sort();
47
48 if (siblingModules.length === 0) {
49 // No module to add in.
50 return;
51 }
52
53 const siblingModulePath = `${options.path}/${siblingModules[0]}`;
54 const logMessage = 'console.log(`page got message: ${data}`);';
55 const workerCreationSnippet = `
56if (typeof Worker !== 'undefined') {
57 // Create a new
58 const worker = new Worker(new URL('./${options.name}.worker', import.meta.url));
59 worker.onmessage = ({ data }) => {
60 ${logMessage}
61 };
62 worker.postMessage('hello');
63} else {
64 // Web Workers are not supported in this environment.
65 // You should add a fallback so that your program still executes correctly.
66}
67 `;
68
69 // Append the worker creation snippet.
70 const originalContent = host.readText(siblingModulePath);
71 host.overwrite(siblingModulePath, originalContent + '\n' + workerCreationSnippet);
72
73 return host;
74 };
75}
76
77const webWorkerSchematic: RuleFactory<WebWorkerOptions> = createProjectSchematic(
78 (options, { project }) => {

Callers 1

index.tsFile · 0.85

Calls 4

debugMethod · 0.65
getDirMethod · 0.65
readTextMethod · 0.65
overwriteMethod · 0.65

Tested by

no test coverage detected