本文整理匯總了TypeScript中@angular-devkit/schematics.Tree.overwrite方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript Tree.overwrite方法的具體用法?TypeScript Tree.overwrite怎麽用?TypeScript Tree.overwrite使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類@angular-devkit/schematics.Tree
的用法示例。
在下文中一共展示了Tree.overwrite方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。
示例1: addResetCss
export function addResetCss(host: Tree): boolean {
const config = getWorkspace(host);
const project = config.projects[config.defaultProject] as WorkspaceProject<ProjectType.Application>;
let addPackage;
const styleExts = ['scss', 'sass', 'css', 'less', 'styl'];
const styleExt = styleExts.find(ext => host.exists(path.posix.join(project.sourceRoot, `styles.${ext}`)));
if (!styleExt) {
return false;
}
const stylesFile = path.posix.join(project.sourceRoot, `styles.${styleExt}`);
switch (styleExt) {
case 'sass':
case 'scss':
let content = host.read(stylesFile).toString();
if (content.indexOf(`~minireset.css/minireset`) === -1) {
content = scssImport + content;
host.overwrite(stylesFile, content);
addPackage = resetPackage;
}
break;
case 'css':
case 'less':
case 'styl':
if (!project.architect ||
!project.architect.build ||
project.projectType !== ProjectType.Application) {
return false;
}
if (project.architect.build.options.styles) {
project.architect.build.options.styles =
[cssImport, ...project.architect.build.options.styles];
} else {
project.architect.build.options.styles = [cssImport];
}
host.overwrite(getWorkspacePath(host), JSON.stringify(config, null, 2));
addPackage = resetPackage;
break;
default:
break;
}
if (addPackage) {
const targetFile = 'package.json';
if (host.exists(targetFile)) {
const pkgJson = JSON.parse(host.read(targetFile).toString());
pkgJson.dependencies = Object.assign({}, addPackage, pkgJson.dependencies);
host.overwrite(targetFile, JSON.stringify(pkgJson, null, 2) + '\n');
return true;
}
}
return false;
}
示例2: return
return (tree: Tree, context: SchematicContext) => {
const pkgPath = '/package.json';
const buffer = tree.read(pkgPath);
if (buffer == null) {
throw new SchematicsException('Could not read package.json');
}
const content = buffer.toString();
const pkg = JSON.parse(content);
if (pkg === null || typeof pkg !== 'object' || Array.isArray(pkg)) {
throw new SchematicsException('Error reading package.json');
}
const dependencyCategories = ['dependencies', 'devDependencies'];
dependencyCategories.forEach(category => {
const packageName = `@ngrx/${name}`;
if (pkg[category] && pkg[category][packageName]) {
const firstChar = pkg[category][packageName][0];
const suffix = match(firstChar, '^') || match(firstChar, '~');
// TODO: remove beta
pkg[category][packageName] = `${suffix}6.0.0`;
}
});
tree.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
context.addTask(new NodePackageInstallTask());
return tree;
};
示例3: Readable
return new Observable<Tree>(obs => {
const input = new Readable({
encoding: 'utf8',
read(): void {
this.push(buffer);
this.push(null);
},
});
const chunks: Array<Buffer> = [];
const output = new Writable({
write(chunk: string | Buffer, encoding: string, callback: Function): void {
chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk);
callback();
},
final(callback: (error?: Error) => void): void {
const full = Buffer.concat(chunks);
host.overwrite(path, full.toString());
callback();
obs.next(host);
obs.complete();
},
});
input.pipe(rewriter).pipe(output);
});
示例4: return
return (host: Tree) => {
host.overwrite('src/app/app.component.html', `<a href="https://github.com/NG-ZORRO/ng-zorro-antd" target="_blank" style="display: flex;align-items: center;justify-content: center;height: 100%;width: 100%;">
<img height="400" src="https://img.alicdn.com/tfs/TB1MGSRv21TBuNjy0FjXXajyXXa-89-131.svg">
</a>
`);
return host;
};
示例5: return
return (host: Tree, context: SchematicContext) => {
const workspace = getWorkspace(host);
const project = workspace.projects[options.project as string];
let path: string;
if (project && project.architect && project.architect.build &&
project.architect.build.options.index) {
path = project.architect.build.options.index;
} else {
throw new SchematicsException('Could not find index file for the project');
}
const buffer = host.read(path);
if (buffer === null) {
throw new SchematicsException(`Could not read index file: ${path}`);
}
const content = buffer.toString();
const lines = content.split('\n');
let closingHeadTagLineIndex = -1;
let closingHeadTagLine = '';
let closingBodyTagLineIndex = -1;
let closingBodyTagLine = '';
lines.forEach((line: string, index: number) => {
if (/<\/head>/.test(line) && closingHeadTagLineIndex === -1) {
closingHeadTagLine = line;
closingHeadTagLineIndex = index;
}
if (/<\/body>/.test(line) && closingBodyTagLineIndex === -1) {
closingBodyTagLine = line;
closingBodyTagLineIndex = index;
}
});
const headTagIndent = getIndent(closingHeadTagLine) + ' ';
const itemsToAddToHead = [
'<link rel="manifest" href="manifest.json">',
'<meta name="theme-color" content="#1976d2">',
];
const textToInsertIntoHead = itemsToAddToHead
.map(text => headTagIndent + text)
.join('\n');
const bodyTagIndent = getIndent(closingBodyTagLine) + ' ';
const itemsToAddToBody
= '<noscript>Please enable JavaScript to continue using this application.</noscript>';
const textToInsertIntoBody = bodyTagIndent + itemsToAddToBody;
const updatedIndex = [
...lines.slice(0, closingHeadTagLineIndex),
textToInsertIntoHead,
...lines.slice(closingHeadTagLineIndex, closingBodyTagLineIndex),
textToInsertIntoBody,
...lines.slice(closingBodyTagLineIndex),
].join('\n');
host.overwrite(path, updatedIndex);
return host;
};
示例6: SchematicsException
(tree: Tree) => {
const packageJsonContent = tree.read('/package.json');
if (!packageJsonContent) {
throw new SchematicsException('Could not find package.json.');
}
const packageJson = parseJson(packageJsonContent.toString(), JsonParseMode.Strict);
if (packageJson === null || typeof packageJson !== 'object' || Array.isArray(packageJson)) {
throw new SchematicsException('Could not parse package.json.');
}
for (const field of kPackageJsonDependencyFields) {
const deps = packageJson[field];
if (!deps || typeof deps !== 'object' || Array.isArray(deps)) {
continue;
}
for (const depName of Object.keys(deps)) {
if (allVersions[depName]) {
deps[depName] = allVersions[depName];
}
}
}
tree.overwrite('/package.json', JSON.stringify(packageJson, null, 2) + '\n');
return tree;
},
示例7: return
return (host: Tree) => {
const workspace = getWorkspace(host);
if (!workspace.projects[options.clientProject]) {
throw new SchematicsException(`Client app ${options.clientProject} not found.`);
}
const clientProject = workspace.projects[options.clientProject];
const projectTargets = getProjectTargets(clientProject);
const builderOptions: JsonObject = {
outputPath: `dist/${options.clientProject}-server`,
main: `${clientProject.root}src/main.server.ts`,
tsConfig: join(tsConfigDirectory, `${options.tsconfigFileName}.json`),
};
const serverTarget: JsonObject = {
builder: '@angular-devkit/build-angular:server',
options: builderOptions,
};
projectTargets.server = serverTarget;
const workspacePath = getWorkspacePath(host);
host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));
return host;
};
示例8: return
return (host: Tree, context: SchematicContext) => {
if (host.exists('package.json')) {
const jsonStr = host.read('package.json') !.toString('utf-8');
const json = JSON.parse(jsonStr);
// If there are no dependencies, create an entry for dependencies.
const type = 'dependencies';
if (!json[type]) {
json[type] = {};
}
// If not already present, add the dependency.
const pkg = 'document-register-element';
const version = '^1.7.2';
if (!json[type][pkg]) {
json[type][pkg] = version;
}
// Write the JSON back to package.json
host.overwrite('package.json', JSON.stringify(json, null, 2));
context.logger.log('info', 'Added `document-register-element` as a dependency.');
// Install the dependency
context.addTask(new NodePackageInstallTask());
}
return host;
};
示例9: return
return (host: Tree) => {
const workspace = getWorkspace(host);
if (!workspace.projects[options.clientProject]) {
throw new SchematicsException(`Client app ${options.clientProject} not found.`);
}
const clientProject = workspace.projects[options.clientProject];
if (!clientProject.architect) {
throw new Error('Client project architect not found.');
}
const builderOptions: JsonObject = {
outputPath: `dist/${options.clientProject}-server`,
main: `${clientProject.root}src/main.server.ts`,
tsConfig: `${clientProject.root}src/tsconfig.server.json`,
};
const serverTarget: JsonObject = {
builder: '@angular-devkit/build-angular:server',
options: builderOptions,
};
clientProject.architect.server = serverTarget;
const workspacePath = getWorkspacePath(host);
host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));
return host;
};
示例10: return
return (host: Tree, context: SchematicContext) => {
const polyfillName = 'custom-elements';
const polyfillPath = 'node_modules/@webcomponents/custom-elements/src/native-shim.js';
try {
const angularJsonFile = host.read('angular.json');
if (angularJsonFile) {
const angularJsonFileObject = JSON.parse(angularJsonFile.toString('utf-8'));
const project = options.project ? options.project : Object.keys(angularJsonFileObject['projects'])[0];
const projectObject = angularJsonFileObject.projects[project];
const targets = projectObject.targets ? projectObject.targets : projectObject.architect;
const scripts = targets.build.options.scripts;
scripts.push({
input: polyfillPath
});
host.overwrite('angular.json', JSON.stringify(angularJsonFileObject, null, 2));
}
} catch (e) {
context.logger.log('error', `đŤ Failed to add the polyfill "${polyfillName}" to scripts`);
}
context.logger.log('info', `â
ď¸ Added "${polyfillName}" polyfill to scripts`);
return host;
};
示例11: return
return (host: Tree, context: SchematicContext) => {
context.logger.info(`Updating karma configuration`);
try {
const karmaPath = config && config.test && config.test.karma && config.test.karma.config
? config.test.karma.config
: defaults.karma;
const buffer = host.read(karmaPath);
if (buffer !== null) {
let content = buffer.toString();
// Replace the 1.0 files and preprocessor entries, with and without comma at the end.
// If these remain, they will cause the `ng test` to fail.
content = content.replace(`{ pattern: './src/test.ts', watched: false },`, '');
content = content.replace(`{ pattern: './src/test.ts', watched: false }`, '');
content = content.replace(`'./src/test.ts': ['@angular/cli'],`, '');
content = content.replace(`'./src/test.ts': ['@angular/cli']`, '');
content = content.replace(/angularCli[^}]*},?/, '');
// Replace 1.x plugin names.
content = content.replace(/@angular\/cli/g, '@angular-devkit/build-angular');
// Replace code coverage output path.
content = content.replace('reports',
`dir: require('path').join(__dirname, 'coverage'), reports`);
host.overwrite(karmaPath, content);
}
} catch { }
return host;
};
示例12: return
return (host: Tree, context: SchematicContext) => {
const workspacePath = getWorkspacePath(host);
const workspace = getWorkspace(host);
const project = workspace.projects[options.project as string];
if (!project) {
throw new Error(`Project is not defined in this workspace.`);
}
const assetEntry = join(normalize(project.root), 'src', 'manifest.json');
if (!project.architect) {
throw new Error(`Architect is not defined for this project.`);
}
const architect = project.architect;
['build', 'test'].forEach((target) => {
const applyTo = architect[target].options;
if (!applyTo.assets) {
applyTo.assets = [assetEntry];
} else {
applyTo.assets.push(assetEntry);
}
});
host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));
return host;
};
示例13: updateFile
function updateFile(remoteFiles: Tree, { path, file }: { path: string, file: FileEntry }) {
if (!file) {
console.log(`missing: ${path}`)
}
remoteFiles.overwrite(path, file.content);
}
示例14: return
return (host: Tree, context: SchematicContext) => {
context.logger.debug('updating config file.');
const workspacePath = getWorkspacePath(host);
const workspace = getWorkspace(host);
const project = workspace.projects[options.project as string];
if (!project) {
throw new Error(`Project is not defined in this workspace.`);
}
if (!project.architect) {
throw new Error(`Architect is not defined for this project.`);
}
if (!project.architect[options.target]) {
throw new Error(`Target is not defined for this project.`);
}
let applyTo = project.architect[options.target].options;
if (options.configuration &&
project.architect[options.target].configurations &&
project.architect[options.target].configurations[options.configuration]) {
applyTo = project.architect[options.target].configurations[options.configuration];
}
applyTo.serviceWorker = true;
host.overwrite(workspacePath, JSON.stringify(workspace, null, 2));
return host;
};
示例15: return
return (tree: Tree, _context: SchematicContext) => {
const localFiles = url("./files")(_context) as Tree;
const updateFiles = getUpdateFiles(localFiles);
const createFiles = getCreateFiles(localFiles);
if (updateFiles.length > 0) {
updateFiles.forEach(f => updateFile(tree, f));
}
if (createFiles.length > 0) {
createFiles.forEach(f => createFile(tree, f));
}
const config = tree.read(".angular-cli.json");
if (config) {
const asJson = JSON.parse(config.toString());
asJson.apps[0].assets.push("config.json");
tree.overwrite(".angular-cli.json", JSON.stringify(asJson, null, 2));
}
// angular 6
const configA6 = tree.read("angular.json");
if (configA6) {
const asJson = JSON.parse(configA6.toString());
Object.entries(asJson.projects).forEach(([,value] : any) => {
const options = value.architect &&
value.architect.build &&
value.architect.build.options;
const assets = options && options.assets;
if (assets) {
assets.push("src/config.json");
}
const styles = options && options.styles;
if (styles) {
styles.push("src/theme.css");
}
});
tree.overwrite("angular.json", JSON.stringify(asJson, null, 2));
}
return tree;
};