Just as this document said,
.props is added at the top of the project file; .targets is added at
the bottom.
example.props
will be read first when you install the nuget package into your project.
Therefore, properties will be available at the start of the build process.
It is usually used to define new global properties, or several new items
which can include some files into your project. Properties and items will be executed at this moment.
example.targets
will be read when you build the project with the installed nuget package.
Nuget will import .props
file very early in Microsoft.Common.props
.
And the principle is actually the same as described in this document.
In more detail, when you install a nuget package in the project, nuget will read the csproj
file(add the reference node into csproj
file).
Because when a nuget is installed, it will read a part of the csproj
file, and only the content of the header part will be read, such as Microsoft.Common.props
file, and the .props
file is imported before it. So when you install the nuget package, the .props
file will be read in its entirety, so any xml node of its content will be read and executed first.
Therefore, it will work when you install the nuget package.
However, .targets
will be imported at the bottom of the csproj
file. So when the nuget package is installed, it cannot reach there and the file cannot be read at all, so the file will only be read when the project is built.
In fact, .props
file is read twice. One time is when nuget was installed, and another time is when you are building the project, but .targets
can only be read when building the project.
Update 1
Note:
For the target of MSBuild, it is special. Some tasks like copy task are written under a target. But if you execute a target with .props or .targets, you should execute the build process. So if you want to the target to be executed under installation process of nuget package, it obviously doesn't work. And you should execute build process to execute it. And when you install the nuget package, it will not execute the build process.
So as I said before, .props
and .targets
are the same when you use a target. When MSBuild reads the .props
or .targets
and enter the target, since the condition is like BeforeTargets="Build"
, however, it is under installation process rather than build process so far. And BeforeTargets="Build"
needs build process. So it will skip it.
This happens 'once'
means msbuild reads the file first under the nuget installation process. It will get the properties or items which can include some files into your main project. But target depends on the build process, so MSBuild will skip it under the nuget installation process(which not execute the build yet).