我目前正在构建一个angular应用程序,它将被制作成docker映像。在制作此图像之后,它应该可供几个人使用。
问题是我无法将变量从docker-compose传递给angular应用程序。
version: "3.6"
services:
dashboard:
image: imagename
build:
context: .
ports: ["4200:8080"]
volumes: ["./dev/config.json:/usr/share/nginx/html/dashboard/assets/config/conf.json"]
environment:
- KEY=EnvToBePassed
创建assets/env.js
(function(window) {
window["env"] = window["env"] || {};
// Environment variables
window["env"]["apiUrl"] = "../assets/lorem.json";
window["env"]["CompanyName"] = "Company name";
})(this);
创建资产/env.template.js
(function(window) {
window["env"] = window["env"] || {};
// Environment variables
window["env"]["apiUrl"] = "../assets/lorem.json";
window["env"]["CompanyName"] = "Company name";
})(this);
在Dockerfile
中调用CMD ["/bin/sh", "-c", "envsubst < /usr/share/nginx/html/assets/env.template.js > /usr/share/nginx/html/assets/env.js && exec nginx -g 'daemon off;'"]
Environment.ts
export const environment = {
production: false,
apiUrl: "../assets/lorem.json",
CompanyName: "Company name"
};
Environment.prod.ts
export const environment = {
production: false,
// @ts-ignore
apiUrl: window["env"]["apiUrl"] || "../assets/lorem.json",
// @ts-ignore
CompanyName: window["env"]["CompanyName"] || "Company name"
};
从index.html
中调用<script src="./assets/env.js"></script>