当 Angular 应用程序运行时,环境将是配置的好地方,但在这里我们尝试根据配置文件运行 cli,我想在angular.json
文件中设置它但我面临死胡同,所以我去写节点脚本将从文件中获取配置,然后运行该配置的 cli 库,也许有更好的方法,但这就是我们提出的。
我在这里使用过 ts-node
运行.ts
import { exec } from 'child_process';
import { environment as dev } from './src/environments/environment';
import { environment as prod } from './src/environments/environment.prod';
function run(command: string): void {
exec(command).stdout.on('data', (data) => {
console.log(data.toString());
});
}
const target = process.argv.slice(2)[0] || 'dev';
console.log(` running in => ${target} `);
switch (target) {
case 'prod': {
run(`ng s --host ${prod.url} --port ${prod.port} `);
break;
}
default: {
run(`ng s --host ${dev.url} --port ${dev.port} `);
}
}
配置文件run-tsconfig.json
(我从 tsconfig.json 复制了这个)
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"module": "commonjs",
"moduleResolution": "node",
"importHelpers": true,
"target": "es2015",
"typeRoots": [
"node_modules/@types"
]
}
}
环境.prod.ts
export const environment = {
production: true,
url: '127.0.0.1',
port: 2000
};
环境.ts
export const environment = {
production: false,
url: '127.0.0.1',
port: 3000
};
运行生产 url 的 cli serv 库
ts-node --project run-tsconfig.json run.ts prod
默认会从 environment.ts (dev) 中读取 url 信息
ts-node --project run-tsconfig.json run.ts