新手求助:如何不使用CLI构建用于生产环境的Angular 2应用
嘿,作为一个经常折腾Angular项目的开发者,我完全理解你想脱离CLI手动构建生产环境应用的想法——这确实能帮你更深入理解Angular的底层工作流程。下面是我整理的具体步骤,一步步来就行:
一、搭建基础项目结构
先手动创建如下目录和文件,这是最精简的生产环境项目骨架:
your-project/ ├── src/ │ ├── app/ │ │ ├── app.component.ts │ │ └── app.module.ts │ ├── main.ts │ ├── index.html │ └── styles.css ├── package.json ├── tsconfig.json ├── webpack.common.js └── webpack.prod.js
二、配置依赖与构建脚本
打开package.json,添加必要的依赖和生产构建脚本。注意区分生产依赖(运行时必需)和开发依赖(构建时用):
{ "name": "angular2-manual-prod", "version": "1.0.0", "scripts": { "build:prod": "webpack --config webpack.prod.js" }, "dependencies": { "@angular/common": "^2.4.10", "@angular/compiler": "^2.4.10", "@angular/core": "^2.4.10", "@angular/platform-browser": "^2.4.10", "@angular/platform-browser-dynamic": "^2.4.10", "core-js": "^2.5.7", "rxjs": "^5.5.12", "zone.js": "^0.8.29" }, "devDependencies": { "webpack": "^4.46.0", "webpack-cli": "^3.3.12", "webpack-merge": "^4.2.2", "typescript": "^2.9.2", "ts-loader": "^5.4.5", "html-webpack-plugin": "^3.2.0", "mini-css-extract-plugin": "^0.8.2", "css-loader": "^3.6.0", "terser-webpack-plugin": "^1.4.5", "optimize-css-assets-webpack-plugin": "^5.0.8" } }
执行npm install安装所有依赖。
三、配置TypeScript编译规则
创建tsconfig.json,确保编译输出符合生产环境要求:
{ "compilerOptions": { "target": "es5", "module": "es2020", "moduleResolution": "node", "sourceMap": false, // 生产环境关闭sourceMap以减小体积 "emitDecoratorMetadata": true, "experimentalDecorators": true, "strict": true, "noImplicitAny": true, "outDir": "./dist", "lib": ["es2015", "dom"] }, "include": ["src/**/*"], "exclude": ["node_modules"] }
四、配置Webpack生产构建
先写通用配置webpack.common.js:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/main.ts', resolve: { extensions: ['.ts', '.js'] }, module: { rules: [ { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ }, { test: /\.css$/, use: ['style-loader', 'css-loader'] } ] }, plugins: [ new HtmlWebpackPlugin({ template: './src/index.html', minify: { // 生产环境会进一步压缩 removeComments: true, collapseWhitespace: true } }) ] };
再写生产环境专属配置webpack.prod.js,用webpack-merge合并通用配置,开启压缩和优化:
const merge = require('webpack-merge'); const common = require('./webpack.common.js'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); module.exports = merge(common, { mode: 'production', output: { filename: '[name].[contenthash].js', // 加contenthash实现缓存优化 path: path.resolve(__dirname, 'dist') }, module: { rules: [ { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'] // 抽离CSS为单独文件 } ] }, optimization: { minimizer: [ new TerserPlugin({ // 压缩JS parallel: true, sourceMap: false }), new OptimizeCSSAssetsPlugin({}) // 压缩CSS ], splitChunks: { // 分割vendor和app代码,优化加载 chunks: 'all' } }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].[contenthash].css' }) ] });
五、编写基础Angular应用代码
先写src/app/app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: `<h1>Hello, Angular 2 Production Build!</h1>` }) export class AppComponent { }
然后是src/app/app.module.ts:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [BrowserModule], declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule { }
接着是入口文件src/main.ts,记得开启生产模式:
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; // 生产环境启用生产模式,禁用开发模式的断言和检查 enableProdMode(); platformBrowserDynamic().bootstrapModule(AppModule);
最后是src/index.html:
<!DOCTYPE html> <html> <head> <title>Angular 2 Production App</title> </head> <body> <app-root></app-root> </body> </html>
六、执行生产构建并验证
运行命令:
npm run build:prod
执行完成后,dist文件夹里会生成带有contenthash的JS、CSS和压缩后的HTML文件。你可以用任何静态服务器(比如serve包)来测试:
npx serve dist
打开浏览器访问对应的地址,就能看到你的生产环境Angular 2应用了。
几个关键注意点
- 生产模式必须开启:
enableProdMode()会关闭Angular的开发时检查和断言,大幅提升运行性能。 - 缓存优化:用
[contenthash]命名打包文件,只有当文件内容变化时hash才会变,浏览器会自动缓存未变化的文件。 - 代码分割:Webpack的
splitChunks会把第三方依赖(比如Angular核心库)和你的业务代码分开打包,用户再次访问时不需要重新下载未更新的依赖包。
内容的提问来源于stack exchange,提问作者Shiva
相关产品推荐
相关产品推荐

