问题
I currently have an angular '2' application inside of a .NET 4.6 project. It is working nicely however I have question with regards to bundling. The application was created using the latest angular CLI and I have a preference to building/bundling the application with it. The bundle's webpack creates are fantastic from my experience.
My question to you is do you have any recommendations/idea's with regards to bundling and thus consuming this bundle in a .NET MVC application? I have seen some other threads where developers have used a gulp file that does the ng build command then transports this output to another location to be consumed.
Any advice would be appreciated.
Thomas
回答1:
I resolved this. I have implemented what I think is a clean solution.
For any that are interested, my answer is below:
Have an 'angular' folder at the root of your project, or any other name you wish to choose.
Inside of this you have your angular-cli.json and package.json files.
In the case that you are creating a nuget package later down the line for a deployment (most likely not) then set the "outDir" in your angular/src/app/tsconfig.json to "../out-tsc". This means you can add the "dist" folder to the package without including the 'out-tsc' folder as well.
You must have the angular cli installed globally in your user account's npm folder. Run npm install -g @angular/cli to do this.
Have a blank index.html at the angular/src level. (unless you specifically need to add something to this).
Configure your root tsconfig (of your .net project) to exclude the 'angular' folder.
You need to set up a pre-build event in your .csproj. This needs to cd into the angular directory, run npm install, then ng build if in debug, or ng build --prod if in release. To determine if your proj is in debug/release the macro is $(ConfigurationName). For my solution I created a powershell script that took the ConfigurationName as an argument and ran npm install then ng build. I ran this script as a pre-build event in the .csproj. You could add the global install of the angular cli here as well but I skipped this.
To include your bundled angular files into your MVC view I used an import link:
<link rel="import" href="/angular/dist/index.html">
This doesn't work in browsers other than chrome so I added a polyfill above it. This polyfill is from webcomponentsjs:
<script async src="~/Scripts/polyfills/webcomponentsjs/lite.js" type="text/javascript"></script>
<link rel="import" href="/angular/dist/index.html">
The resulting view:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<app-root>Loading...</app-root>
<script async src="~/Scripts/polyfills/webcomponentsjs/lite.js" type="text/javascript"></script>
<link rel="import" href="/angular/dist/index.html">
Now when you build then boot up your .NET MVC application and go to this view your angular application will appear.
Kind regards
来源:https://stackoverflow.com/questions/43050799/building-bundling-an-angular-2-application-for-a-net-mvc-project