如何基于ASP.NET MVC(.NET Framework)搭配Webpack搭建Angular 4?
Hey there! Let's walk through setting up an ASP.NET MVC (.NET Framework) project that integrates Angular 4 with Webpack step by step. I've broken this down into manageable chunks so you can follow along easily:
1. Environment Setup
First, make sure you have these tools installed:
- Node.js 8.x+ (comes with npm; Angular 4 requires this minimum version for compatibility)
- Visual Studio 2017/2019 (ensure you've selected the "ASP.NET and Web Development" workload during installation)
- Install global npm packages needed for the build pipeline:
Note: We're using Angular CLI v1.7.4 because it's the last stable version compatible with Angular 4.npm install -g webpack webpack-cli typescript @angular/cli@1.7.4
2. Create the ASP.NET MVC (.NET Framework) Project
- Open Visual Studio, click "Create a new project"
- Search for ASP.NET Web Application (.NET Framework), name your project (e.g.,
Angular4MvcWebpack), and select .NET Framework 4.6.1 or higher (compatible with Angular 4) - In the template selection screen, choose MVC, uncheck "Configure HTTPS" (you can set this up later), then click "Create"
3. Initialize npm Project
- Navigate to your project's root directory, right-click and select "Open in Terminal" (or use a command prompt to reach the folder)
- Run this command to initialize npm and generate a
package.jsonfile:npm init -y
4. Install Angular 4 & Dependencies
- Install core Angular 4 packages (we're using specific versions to avoid compatibility issues):
npm install @angular/core@4.4.7 @angular/common@4.4.7 @angular/compiler@4.4.7 @angular/platform-browser@4.4.7 @angular/platform-browser-dynamic@4.4.7 @angular/http@4.4.7 @angular/router@4.4.7 @angular/forms@4.4.7 --save - Install development dependencies for TypeScript and Webpack:
npm install typescript@2.3.4 ts-loader@3.5.0 webpack@3.12.0 webpack-dev-server@2.11.2 html-webpack-plugin@2.30.1 clean-webpack-plugin@0.1.19 @types/node@8.10.61 @types/core-js@2.5.4 --save-dev
5. Configure TypeScript
- Create a
tsconfig.jsonfile in your project root with these settings:{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": ["es2015", "dom"], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true, "typeRoots": ["./node_modules/@types/"] }, "exclude": ["node_modules", "dist"] }
6. Configure Webpack
- Create a
webpack.config.jsfile in the project root to define your build pipeline:const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: './app/main.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.[hash].js' }, module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ } ] }, resolve: { extensions: ['.ts', '.js'] }, plugins: [ new CleanWebpackPlugin(['dist']), new HtmlWebpackPlugin({ template: './app/index.html' }) ], devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 4200 } };
7. Set Up Angular 4 Project Structure
Create an
appfolder in your project root, then add these files and folders inside it:main.ts(Angular entry point)app.module.ts(root Angular module)app.component.ts(root component)app.component.html(component template)index.html(base HTML for Angular)
Here's the content for each file:
main.ts:import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule);app.module.ts:import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent] }) export class AppModule { }app.component.ts:import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { title = 'Angular 4 + ASP.NET MVC'; }app.component.html:<h1>{{ title }}</h1> <p>This is an Angular 4 component running inside ASP.NET MVC!</p>index.html:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Angular 4 MVC App</title> </head> <body> <app-root></app-root> </body> </html>
8. Integrate Angular with ASP.NET MVC
- Open
Views/Home/Index.cshtmland replace its content with this:@{ ViewBag.Title = "Home Page"; } <!-- Container for Angular app --> <div id="angular-app"> <app-root></app-root> </div> <!-- Load Webpack-generated bundle --> <script src="~/dist/bundle.js"></script> - Open
App_Start/RouteConfig.csto ensure the default route points to the home page:public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } - Configure static file access by adding this to your
Web.configinside the<system.webServer>node:<staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> <mimeMap fileExtension=".ts" mimeType="application/typescript" /> </staticContent> <handlers> <add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Either" requireAccess="Read" /> </handlers>
9. Build & Run the Project
- For development, run Webpack Dev Server to enable hot reloading:
npm run dev - To build a production-ready bundle, update your
package.json'sscriptssection:
Then run:"scripts": { "build": "webpack --mode production", "dev": "webpack-dev-server --mode development" }npm run build - Finally, press F5 in Visual Studio to launch the ASP.NET MVC project. You'll see the Angular 4 component rendered on the home page!
内容的提问来源于stack exchange,提问作者Avishek Dutta
相关产品推荐
相关产品推荐

