After a long search, reading and experimenting, i solved by simply adding the enviroment variable ASPNETCORE_ENVIRONMENT
in my .pubxml
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ASPNETCORE_ENVIRONMENT>Test</ASPNETCORE_ENVIRONMENT>
</PropertyGroup>
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
.....
</PropertyGroup>
</Project>
I use it to select my react app's build environment, on publish, my .csproj
looks like:
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:$(ASPNETCORE_ENVIRONMENT.ToLower())" />
...
</Target>
Finally my react app's package.json
:
"scripts": {
"start": "env-cmd -f .env.development react-scripts start",
"build:production": "env-cmd -f .env.production react-scripts build",
"build:staging": "env-cmd -f .env.staging react-scripts build",
"build:test": "env-cmd -f .env.test react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"mock:api": "json-server --watch db.json --port 4000"
},
I intentionally removed "build": "react-scripts build"
line, so environment is always supplied.
EDIT:
I also added PropertyGroup
for setting EnvironmentName
in .csproj
file, so on publishing, my web.config
will set the ASPNETCORE_ENVIRONMENT
as environment variable, as defined in my .pubxml
, dynamically:
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:$(ASPNETCORE_ENVIRONMENT.ToLower())" />
<PropertyGroup>
<EnvironmentName>$(ASPNETCORE_ENVIRONMENT)</EnvironmentName>
</PropertyGroup>
</Target>