如何在Nx单体仓库中替换Angular应用的环境配置?
问题场景
已将测试应用部署至Firebase Hosting,点击注册/登录按钮调用signInWithPopup(auth, provider)时,弹出窗口提示:“无法访问此网站。127.0.0.1拒绝连接。”
推测错误原因是构建过程中未切换环境配置,当前代码中会根据environment.useEmulators判断是否连接本地Auth模拟器:
provideFirebaseApp(() => initializeApp(environment.firebaseConfig)), provideAuth(() => { const auth = getAuth(); if (environment.useEmulators) { connectAuthEmulator(auth, 'http://127.0.0.1:9099'); } return auth; }),
此前在Angular应用中使用angular filereplacements替换配置,现需了解如何在Nx单体仓库中替换Angular应用的环境配置,当前应用的project.json构建配置如下:
"targets": { "build": { "executor": "@angular-devkit/build-angular:application", "outputs": ["{options.outputPath}"], "options": { "outputPath": "dist/apps/qubitme", "index": "apps/qubitme/src/index.html", ... }, "configurations": { "production": { ... "outputHashing": "all" }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true } }, "defaultConfiguration": "production" },
Nx中替换Angular环境配置的方法
在Nx的project.json中,可通过配置fileReplacements实现环境文件替换,步骤如下:
- 准备环境文件
确保应用目录下有对应环境的配置文件:
apps/qubitme/src/environments/environment.ts:开发环境配置(useEmulators: true,连接本地模拟器)apps/qubitme/src/environments/environment.prod.ts:生产环境配置(useEmulators: false,填写Firebase正式环境的firebaseConfig)
- 修改project.json的build配置
在build目标的configurations中,给每个环境添加fileReplacements字段:
"targets": { "build": { "executor": "@angular-devkit/build-angular:application", "outputs": ["{options.outputPath}"], "options": { "outputPath": "dist/apps/qubitme", "index": "apps/qubitme/src/index.html", ... }, "configurations": { "production": { ... "outputHashing": "all", "fileReplacements": [ { "replace": "apps/qubitme/src/environments/environment.ts", "with": "apps/qubitme/src/environments/environment.prod.ts" } ] }, "development": { "optimization": false, "extractLicenses": false, "sourceMap": true, "fileReplacements": [ { "replace": "apps/qubitme/src/environments/environment.ts", "with": "apps/qubitme/src/environments/environment.ts" } ] } }, "defaultConfiguration": "production" },
- 构建时指定环境
- 构建生产环境(默认配置):
nx build qubitme - 手动指定生产环境:
nx build qubitme --configuration=production - 构建开发环境:
nx build qubitme --configuration=development
- 部署验证
部署Firebase前,确认使用的是生产环境构建的产物(dist/apps/qubitme目录),此时应用会使用正式的Firebase Auth配置,不再尝试连接本地模拟器。
内容的提问来源于stack exchange,提问作者pax
相关产品推荐
相关产品推荐

