本文整理匯總了TypeScript中@angular-devkit/schematics.Tree.commitUpdate方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Tree.commitUpdate方法的具體用法?TypeScript Tree.commitUpdate怎麽用?TypeScript Tree.commitUpdate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類@angular-devkit/schematics.Tree
的用法示例。
在下文中一共展示了Tree.commitUpdate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: return
return (host: Tree, context: SchematicContext) => {
context.logger.debug('Updating appmodule');
// find app module
const projectTargets = getProjectTargets(host, options.project);
if (!projectTargets.build) {
throw targetBuildNotFoundError();
}
const mainPath = projectTargets.build.options.main;
const modulePath = getAppModulePath(host, mainPath);
context.logger.debug(`module path: ${modulePath}`);
// add import
let moduleSource = getTsSourceFile(host, modulePath);
let importModule = 'ServiceWorkerModule';
let importPath = '@angular/service-worker';
if (!isImported(moduleSource, importModule, importPath)) {
const change = insertImport
(moduleSource, modulePath, importModule, importPath);
if (change) {
const recorder = host.beginUpdate(modulePath);
recorder.insertLeft((change as InsertChange).pos, (change as InsertChange).toAdd);
host.commitUpdate(recorder);
}
}
// add import for environments
// import { environment } from '../environments/environment';
moduleSource = getTsSourceFile(host, modulePath);
importModule = 'environment';
// TODO: dynamically find environments relative path
importPath = '../environments/environment';
if (!isImported(moduleSource, importModule, importPath)) {
const change = insertImport
(moduleSource, modulePath, importModule, importPath);
if (change) {
const recorder = host.beginUpdate(modulePath);
recorder.insertLeft((change as InsertChange).pos, (change as InsertChange).toAdd);
host.commitUpdate(recorder);
}
}
// register SW in app module
const importText =
`ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production })`;
moduleSource = getTsSourceFile(host, modulePath);
const metadataChanges = addSymbolToNgModuleMetadata(
moduleSource, modulePath, 'imports', importText);
if (metadataChanges) {
const recorder = host.beginUpdate(modulePath);
metadataChanges.forEach((change: InsertChange) => {
recorder.insertRight(change.pos, change.toAdd);
});
host.commitUpdate(recorder);
}
return host;
};
示例2: return
return (host: Tree) => {
if (options.skipImport || !options.module) {
return host;
}
const modulePath = options.module;
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString('utf-8');
const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
const componentPath = `/${options.path}/`
+ (options.flat ? '' : strings.dasherize(options.name) + '/')
+ strings.dasherize(options.name)
+ '.component';
const relativePath = buildRelativePath(modulePath, componentPath);
const classifiedName = strings.classify(`${options.name}Component`);
const declarationChanges = addDeclarationToModule(source,
modulePath,
classifiedName,
relativePath);
const declarationRecorder = host.beginUpdate(modulePath);
for (const change of declarationChanges) {
if (change instanceof InsertChange) {
declarationRecorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(declarationRecorder);
if (options.export) {
// Need to refresh the AST because we overwrote the file in the host.
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString('utf-8');
const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
const exportRecorder = host.beginUpdate(modulePath);
const exportChanges = addExportToModule(source, modulePath,
strings.classify(`${options.name}Component`),
relativePath);
for (const change of exportChanges) {
if (change instanceof InsertChange) {
exportRecorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(exportRecorder);
}
return host;
};
示例3: return
return (host: Tree) => {
const clientProject = getProject(host, options.clientProject);
const architect = getProjectTargets(clientProject);
// const mainPath = universalArchitect.build.options.main;
const modulePath = getServerModulePath(host, clientProject, architect);
if (modulePath === null) {
throw new SchematicsException('Universal/server module not found.');
}
let moduleSource = getSourceFile(host, modulePath);
if (!isImported(moduleSource, 'Routes', '@angular/router')) {
const recorder = host.beginUpdate(modulePath);
const routesChange = insertImport(moduleSource,
modulePath,
'Routes',
'@angular/router') as InsertChange;
if (routesChange.toAdd) {
recorder.insertLeft(routesChange.pos, routesChange.toAdd);
}
const imports = getSourceNodes(moduleSource)
.filter(node => node.kind === ts.SyntaxKind.ImportDeclaration)
.sort((a, b) => a.getStart() - b.getStart());
const insertPosition = imports[imports.length - 1].getEnd();
const routeText =
`\n\nconst routes: Routes = [ { path: '${options.route}', component: AppShellComponent }];`;
recorder.insertRight(insertPosition, routeText);
host.commitUpdate(recorder);
}
moduleSource = getSourceFile(host, modulePath);
if (!isImported(moduleSource, 'RouterModule', '@angular/router')) {
const recorder = host.beginUpdate(modulePath);
const routerModuleChange = insertImport(moduleSource,
modulePath,
'RouterModule',
'@angular/router') as InsertChange;
if (routerModuleChange.toAdd) {
recorder.insertLeft(routerModuleChange.pos, routerModuleChange.toAdd);
}
const metadataChange = addSymbolToNgModuleMetadata(
moduleSource, modulePath, 'imports', 'RouterModule.forRoot(routes)');
if (metadataChange) {
metadataChange.forEach((change: InsertChange) => {
recorder.insertRight(change.pos, change.toAdd);
});
}
host.commitUpdate(recorder);
}
return host;
};
示例4: return
return (host: Tree) => {
if (options.skipImport || !options.module) {
return host;
}
const modulePath = options.module;
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString('utf-8');
const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
const pipePath = `/${options.path}/`
+ (options.flat ? '' : strings.dasherize(options.name) + '/')
+ strings.dasherize(options.name)
+ '.pipe';
const relativePath = buildRelativePath(modulePath, pipePath);
const changes = addDeclarationToModule(source, modulePath,
strings.classify(`${options.name}Pipe`),
relativePath);
const recorder = host.beginUpdate(modulePath);
for (const change of changes) {
if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(recorder);
if (options.export) {
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString('utf-8');
const source = ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
const exportRecorder = host.beginUpdate(modulePath);
const exportChanges = addExportToModule(source, modulePath,
strings.classify(`${options.name}Pipe`),
relativePath);
for (const change of exportChanges) {
if (change instanceof InsertChange) {
exportRecorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(exportRecorder);
}
return host;
};
示例5: return
return (host: Tree, context: SchematicContext) => {
const packageJson = 'package.json';
if (!host.exists(packageJson)) {
throw new Error(`Could not find ${packageJson}`);
}
const content = host.read(packageJson).toString();
const jsonAst = parseJsonAst(content);
if (!isJsonAstObject(jsonAst)) {
throw new Error(`Failed to parse JSON for ${packageJson}`);
}
const deps = findPropertyInAstObject(jsonAst, 'dependencies');
if (!isJsonAstObject(deps)) {
throw new Error(`Failed to find dependencies in ${packageJson}`);
}
const rxjs = findPropertyInAstObject(deps, 'rxjs');
if (!rxjs) {
throw new Error(`Failed to find rxjs in dependencies of ${packageJson}`);
}
const value = rxjs.value as string; // value can be version or range
const match = value.match(/(\d)+\.(\d)+.(\d)+$/);
if (match) {
const [_, major, minor] = match;
if (major < '6' || (major === '6' && minor < '4')) {
const recorder = host.beginUpdate(packageJson);
replacePropertyInAstObject(recorder, deps, 'rxjs', '~6.4.0');
host.commitUpdate(recorder);
}
} else {
context.logger.info(
'Could not determine version of rxjs. \n' +
'Please make sure that version is at least 6.4.0.');
}
return host;
};
示例6: return
return (host: Tree) => {
const tsConfigPath = '/tsconfig.json';
const buffer = host.read(tsConfigPath);
if (!buffer) {
return host;
}
const tsCfgAst = parseJsonAst(buffer.toString(), JsonParseMode.Loose);
if (tsCfgAst.kind !== 'object') {
return host;
}
const compilerOptions = findPropertyInAstObject(tsCfgAst, 'compilerOptions');
if (!compilerOptions || compilerOptions.kind !== 'object') {
return host;
}
const importHelpers = findPropertyInAstObject(compilerOptions, 'importHelpers');
if (importHelpers && importHelpers.value === true) {
return host;
}
const recorder = host.beginUpdate(tsConfigPath);
if (importHelpers) {
const { start, end } = importHelpers;
recorder.remove(start.offset, end.offset - start.offset);
recorder.insertLeft(start.offset, 'true');
} else {
insertPropertyInAstObjectInOrder(recorder, compilerOptions, 'importHelpers', true, 4);
}
host.commitUpdate(recorder);
return host;
};
示例7: appendHtmlElementToHead
export function appendHtmlElementToHead(host: Tree, htmlFilePath: string, elementHtml: string) {
const htmlFileBuffer = host.read(htmlFilePath);
if (!htmlFileBuffer) {
throw new SchematicsException(`Could not read file for path: ${htmlFilePath}`);
}
const htmlContent = htmlFileBuffer.toString();
if (htmlContent.includes(elementHtml)) {
return;
}
const headTag = getHtmlHeadTagElement(htmlContent);
if (!headTag) {
throw `Could not find '<head>' element in HTML file: ${htmlFileBuffer}`;
}
// We always have access to the source code location here because the `getHeadTagElement`
// function explicitly has the `sourceCodeLocationInfo` option enabled.
const endTagOffset = headTag.sourceCodeLocation!.endTag.startOffset;
const indentationOffset = getChildElementIndentation(headTag);
const insertion = `${' '.repeat(indentationOffset)}${elementHtml}`;
const recordedChange = host
.beginUpdate(htmlFilePath)
.insertRight(endTagOffset, `${insertion}\n`);
host.commitUpdate(recordedChange);
}
示例8: getNamedImports
visitor.missingInjectablePipes.forEach(data => {
const {classDeclaration, importDeclarationMissingImport} = data;
const sourceFile = classDeclaration.getSourceFile();
const update = tree.beginUpdate(relative(basePath, sourceFile.fileName));
// Note that we don't need to go through the AST to insert the decorator, because the change
// is pretty basic. Also this has a better chance of preserving the user's formatting.
update.insertLeft(classDeclaration.getStart(), `@${INJECTABLE_DECORATOR_NAME}()\n`);
// Add @Injectable to the imports if it isn't imported already. Note that this doesn't deal with
// the case where there aren't any imports for `@angular/core` at all. We don't need to handle
// it because the Pipe decorator won't be recognized if it hasn't been imported from Angular.
if (importDeclarationMissingImport) {
const namedImports = getNamedImports(importDeclarationMissingImport);
if (namedImports) {
update.remove(namedImports.getStart(), namedImports.getWidth());
update.insertRight(
namedImports.getStart(),
printer.printNode(
ts.EmitHint.Unspecified, addImport(namedImports, INJECTABLE_DECORATOR_NAME),
sourceFile));
}
}
tree.commitUpdate(update);
});
示例9: return
return (tree: Tree) => {
const collectionJsonContent = tree.read('/.monorepo.json');
if (!collectionJsonContent) {
throw new Error('Could not find monorepo.json');
}
const collectionJsonAst = parseJsonAst(collectionJsonContent.toString('utf-8'));
if (collectionJsonAst.kind !== 'object') {
throw new Error('Invalid monorepo content.');
}
const packages = collectionJsonAst.properties.find(x => x.key.value == 'packages');
if (!packages) {
throw new Error('Cannot find packages key in monorepo.');
}
if (packages.value.kind != 'object') {
throw new Error('Invalid packages key.');
}
const readmeUrl = `https://github.com/angular/devkit/blob/master/${path}/README.md`;
const recorder = tree.beginUpdate('/.monorepo.json');
appendPropertyInAstObject(
recorder,
packages.value,
options.name,
{
name: options.displayName,
links: [{ label: 'README', url: readmeUrl }],
version: '0.0.1',
hash: '',
},
);
tree.commitUpdate(recorder);
};
示例10: return
return (host: Tree) => {
const workspace = getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const appModulePath = getAppModulePath(host, getProjectMainFile(project));
const moduleSource = getSourceFile(host, appModulePath);
const locale = getCompatibleLocal(options);
const localePrefix = locale.split('_')[ 0 ];
const recorder = host.beginUpdate(appModulePath);
const changes = [
insertImport(moduleSource, appModulePath, 'NZ_I18N',
'ng-zorro-antd'),
insertImport(moduleSource, appModulePath, locale,
'ng-zorro-antd'),
insertImport(moduleSource, appModulePath, 'registerLocaleData',
'@angular/common'),
insertImport(moduleSource, appModulePath, localePrefix,
`@angular/common/locales/${localePrefix}`, true),
registerLocaleData(moduleSource, appModulePath, localePrefix),
...insertI18nTokenProvide(moduleSource, appModulePath, locale)
];
changes.forEach((change) => {
if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}
});
host.commitUpdate(recorder);
return host;
};
示例11: function
return function(host: Tree): Tree {
const workspace = getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
// Because the build setup for the Angular CLI can be changed so dramatically, we can't know
// where to generate anything if the project is not using the default config for build and test.
assertDefaultProjectConfig(project);
const stylesPath = getStylesPath(host, project);
if (stylesPath.endsWith('.less')) {
console.error(`Your project is not using less styles, current file: ${stylesPath}`);
}
const buffer = host.read(stylesPath);
if (buffer) {
const insertion = new InsertChange(
stylesPath,
0,
createCustomTheme(project),
);
const recorder = host.beginUpdate(stylesPath);
recorder.insertLeft(insertion.pos, insertion.toAdd);
host.commitUpdate(recorder);
} else {
console.warn(`Skipped insert style; could not find file: ${stylesPath}`);
}
return host;
};
示例12: return
return (host: Tree) => {
const workspace = getWorkspace(host);
const project = getProjectFromWorkspace(workspace, options.project);
const styleFilePath = getProjectStyleFile(project);
if (!styleFilePath) {
console.warn(red(`Could not find the default style file for this project.`));
console.warn(red(`Please consider manually setting up the Roboto font in your CSS.`));
return;
}
const buffer = host.read(styleFilePath);
if (!buffer) {
console.warn(red(`Could not read the default style file within the project ` +
`(${italic(styleFilePath)})`));
console.warn(red(`Please consider manually setting up the Robot font.`));
return;
}
const htmlContent = buffer.toString();
const insertion = '\n' +
`html, body { height: 100%; }\n` +
`body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }\n`;
if (htmlContent.includes(insertion)) {
return;
}
const recorder = host.beginUpdate(styleFilePath);
recorder.insertLeft(htmlContent.length, insertion);
host.commitUpdate(recorder);
};
示例13: return
return (host: Tree) => {
const tsLintPath = '/tslint.json';
const buffer = host.read(tsLintPath);
if (!buffer) {
return host;
}
const tsCfgAst = parseJsonAst(buffer.toString(), JsonParseMode.Loose);
if (tsCfgAst.kind != 'object') {
return host;
}
const rulesNode = findPropertyInAstObject(tsCfgAst, 'rules');
if (!rulesNode || rulesNode.kind != 'object') {
return host;
}
const recorder = host.beginUpdate(tsLintPath);
rulesNode.properties.forEach(prop => {
const mapping = ruleMapping[prop.key.value];
if (mapping) {
recorder.remove(prop.key.start.offset + 1, prop.key.value.length);
recorder.insertLeft(prop.key.start.offset + 1, mapping);
}
});
host.commitUpdate(recorder);
return host;
};
示例14: return
return (host: Tree) => {
const clientTargets = getClientTargets(host, options);
const mainPath = normalize('/' + clientTargets.build.options.main);
let bootstrapCall: ts.Node | null = findBootstrapModuleCall(host, mainPath);
if (bootstrapCall === null) {
throw new SchematicsException('Bootstrap module not found.');
}
let bootstrapCallExpression: ts.Node | null = null;
let currentCall = bootstrapCall;
while (bootstrapCallExpression === null && currentCall.parent) {
currentCall = currentCall.parent;
if (currentCall.kind === ts.SyntaxKind.ExpressionStatement) {
bootstrapCallExpression = currentCall;
}
}
bootstrapCall = currentCall;
const recorder = host.beginUpdate(mainPath);
const beforeText = `document.addEventListener('DOMContentLoaded', () => {\n `;
const afterText = `\n});`;
recorder.insertLeft(bootstrapCall.getStart(), beforeText);
recorder.insertRight(bootstrapCall.getEnd(), afterText);
host.commitUpdate(recorder);
};
示例15: return
return (host: Tree) => {
if (!options.module) {
return host;
}
const modulePath = options.module;
if (!host.exists(options.module)) {
throw new Error('Specified module does not exist');
}
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString('utf-8');
const source = ts.createSourceFile(
modulePath,
sourceText,
ts.ScriptTarget.Latest,
true
);
const commonImports = [
insertImport(source, modulePath, 'StoreModule', '@ngrx/store'),
];
const reducerPath =
`/${options.path}/` +
(options.flat ? '' : stringUtils.dasherize(options.name) + '/') +
(options.group ? 'reducers/' : '') +
stringUtils.dasherize(options.name) +
'.reducer';
const relativePath = buildRelativePath(modulePath, reducerPath);
const reducerImport = insertImport(
source,
modulePath,
`* as from${stringUtils.classify(options.name)}`,
relativePath,
true
);
const [storeNgModuleImport] = addImportToModule(
source,
modulePath,
`StoreModule.forFeature('${stringUtils.camelize(
options.name
)}', from${stringUtils.classify(options.name)}.reducer)`,
relativePath
);
const changes = [...commonImports, reducerImport, storeNgModuleImport];
const recorder = host.beginUpdate(modulePath);
for (const change of changes) {
if (change instanceof InsertChange) {
recorder.insertLeft(change.pos, change.toAdd);
}
}
host.commitUpdate(recorder);
return host;
};