我将讨论 csproj 配置、package.json npm 配置,当然还有你的 Startup.cs 代码。
.csproj 文件
在您的 csproj 文件的底部,您将找到一组在应用程序发布时运行的 npm 命令。
<!--...-->
<PropertyGroup>
<SpaRoot>ClientApp\</SpaRoot>
</PropertyGroup>
<!--...-->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build -- --prod" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />
<!--...-->
如果您想部署两个应用程序,则需要加倍执行所有这些部署说明。
<!--...-->
<PropertyGroup>
<!--...-->
<SpaRoot>ClientApp\</SpaRoot>
<SpaRoot2>ClientApp2\</SpaRoot2>
<!--...-->
</PropertyGroup>
<!--...-->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<!--...-->
<Exec WorkingDirectory="$(SpaRoot2)" Command="npm install" />
<!--...-->
配置 package.json
在开发过程中,您可能希望 nodejs 来托管应用程序。在这种情况下,我们的服务器没有托管我们的客户端应用程序。
您需要设置 servepath 以匹配您希望客户端应用程序运行的子目录。
// ...
"start": "ng serve --servePath /app/ --baseHref /app/",
// ...
此时,不要忘记更新构建的 baseHref。否则当 csproj 中的脚本调用 build 时,它不会指向正确的 basehref。
"build": "ng build --baseHref /app/",
Startup.cs 配置
还记得我在开发时说过服务器不托管客户端吗?我建议在开发时一次运行一个。重要的是您更新 package.json servePath 以便您测试 url 路径以及所有内容如何链接在一起。
if (env.IsDevelopment())
{
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
// this is calling the start found in package.json
spa.UseAngularCliServer(npmScript: "start");
});
}
else // Production -- in the next section,
最后,我们有了我们希望它在生产中的行为方式。
// how you had it, we will create a map
// for each angular client we want to host.
app.Map(new PathString("/app"), client =>
{
// Each map gets its own physical path
// for it to map the static files to.
StaticFileOptions clientAppDist = new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(
Directory.GetCurrentDirectory(),
@"ClientApp\dist"
)
)
};
// Each map its own static files otherwise
// it will only ever serve index.html no matter the filename
client.UseSpaStaticFiles(clientAppDist);
// Each map will call its own UseSpa where
// we give its own sourcepath
client.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.Options.DefaultPageStaticFileOptions = clientAppDist;
});
});
您可以通过注释掉开发代码并在运行 C# 代码之前在各自的 clientapp 文件夹中运行 npm run build 来测试生产设置。只需确保生成的 dist 文件夹未检入您的 git 存储库。
希望您现在可以更好地了解它在开发环境中的工作原理、创建构建说明以及它将如何在生产环境中运行。