Angular5项目如何在angular.cli.json中配置prod和dev双index.html
Angular5 配置不同环境的 index.html 文件
步骤1:准备环境专属的 index 文件
在项目的src目录下,复制现有index.html,分别命名为index.dev.html(开发环境用)和index.prod.html(生产环境用),按需修改两个文件的内容。
步骤2:修改 angular.cli.json 配置
打开项目根目录下的angular.cli.json,找到apps数组中的目标应用配置(通常是数组第一个元素),按以下方式调整:
- 保留原有基础配置,添加或编辑
configurations字段,分别定义dev和prod环境的专属规则:
"apps": [ { "root": "src", "outDir": "dist", "assets": ["assets", "favicon.ico"], "index": "index.html", // 默认 fallback 的 index 文件 "main": "main.ts", "polyfills": "polyfills.ts", "test": "test.ts", "tsconfig": "tsconfig.app.json", "testTsconfig": "tsconfig.spec.json", "prefix": "app", "styles": ["styles.css"], "scripts": [], "environmentSource": "environments/environment.ts", "environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" }, // 新增/编辑 configurations 字段 "configurations": { "prod": { "index": "index.prod.html", // 指定生产环境用的 index 文件 "fileReplacements": [ { "replace": "environments/environment.ts", "with": "environments/environment.prod.ts" } ], "aot": true, "optimization": true }, "dev": { "index": "index.dev.html" // 指定开发环境用的 index 文件 } } } ]
步骤3:使用对应环境构建/启动项目
- 开发环境构建:执行命令
ng build --env=dev,构建产物会使用index.dev.html - 生产环境构建:执行命令
ng build --env=prod,构建产物会使用index.prod.html - 启动开发服务器时指定环境:
ng serve --env=dev,此时浏览器加载的是index.dev.html
注意:Angular5 使用
--env参数指定环境,而非 Angular6+ 的--configuration,这是你之前报错的原因。
内容的提问来源于stack exchange,提问作者SundaR
相关产品推荐
相关产品推荐

