I want to write a Rule
that overwrites a file every time. In the following and have MergeStrategy
set to Overwrite
:
collection.json
{
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"function": {
"aliases": [ "fn" ],
"factory": "./function",
"description": "Create a function.",
"schema": "./function/schema.json"
}
}
}
function/index.ts
export default function(options: FunctionOptions): Rule {
options.path = options.path ? normalize(options.path) : options.path;
const sourceDir = options.sourceDir;
if (!sourceDir) {
throw new SchematicsException(`sourceDir option is required.`);
}
const templateSource: Source = apply(
url('./files'),
[
template({
...strings,
...options,
}),
move(sourceDir),
]
)
return mergeWith(templateSource, MergeStrategy.Overwrite);
}
files/__path__/__name@dasherize__.ts
export function <%= camelize(name) %>(): void {
}
I run schematics .:function --name=test --dry-run=false
I get
CREATE /src/app/test.ts (33 bytes)
but then, the second time.
ERROR! /src/app/test.ts already exists.
Should it not overwrite the file test.ts with out error?
Edit:
All of the answers work and are great but it seems they are workarounds and no obvious "right" answer and possibly based on preference / opinionated. So not sure how to mark as answered.
This may not be ideal if you are replacing many files. I came across this issue replacing the favicon.ico while adding boilerplate to the project. The solution I use is to explicitly delete it first.
NOTE: This approach no longer works with current versions of Schematics.
The following seems to work for the 0.6.8 schematics.
As a bonus, I no longer need to explicitly delete the file.
Modifying chris' answer I was able to come up with the following solution:
Replace your usage of
apply
with calls to this function.I experienced the same issue. By accident I found that adding a
forEach
into theapply
allowed the files to be deleted and the new files created. This is with @angular-devkit/schematics-cli@0.6.8.Thanks @cgatian for that hint!
Unfortunately it didn't worked to
move
the templates to some location, so I had to add:Until the
MergeStrategy
works as expected,this will do the trick passing the destination path in
options.output
!Thanks again!