在 Angular 中,我想為每個環境使用不同的環境配置。
這意味著,例如,如果我部署到 dev 環境,我希望 Angular 應用程式使用 Dev 變數,如果我部署到 Prod,我希望 Angular 使用 prod 變數。
有沒有辦法做到這一點?例如,創建一個包含所有變數的檔案,然后 Angular 只需查看它所在的環境并選擇正確的變數。
uj5u.com熱心網友回復:
只需在專案根目錄中創建一個新的打字稿檔案,與 pacakage.json 檔案所在的目錄相同,假設您創建一個名為 set-env.ts 的檔案,將此代碼放入檔案中
import { writeFile } from 'fs';
// Configure Angular `environment.ts` file path
const targetPath = './src/environments/environment.ts';
const targetPathProd = './src/environments/environment.prod.ts';
const envConfigFile = `export const environment = {
production: false,
serverURL: 'https://devenviroment.com/api',
someOtherProperty: 'response'
};
`;
const envProdConfigFile = `export const environment = {
production: true,
serverURL: 'https://serverurlproduction.com/api',
someOtherProperty: 'value'
};
`;
console.log('The file `environment.ts` will be written with the following content: \n');
console.log(envConfigFile);
writeFile(targetPath, envConfigFile, function (err) {
if (err) {
throw console.error(err);
} else {
console.log(`Angular environment.ts file generated correctly at ${targetPath} \n`);
}
});
writeFile(targetPathProd, envProdConfigFile, function (err) {
if (err) {
throw console.error(err);
} else {
console.log(`Angular environment.prod.ts file generated correctly at ${targetPath} \n`);
}
});
現在將此行添加到腳本標記內的 package.json 檔案中
"config-env": "ts-node set-env.ts",
"build": "ng build"
現在,當您構建專案時,您可以簡單地使用此命令
npm run config-env & npm run build
npm run config-env 命令將使用您在 set-env.ts 中撰寫的配置覆寫您的環境檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409469.html
標籤:
