|
| 1 | +import * as fs from 'fs'; |
| 2 | + |
| 3 | +interface WebpackPlugin { |
| 4 | + apply(compiler: any): void; |
| 5 | +} |
| 6 | + |
| 7 | +interface NgCliEnvrionmentConfig { |
| 8 | + env?: string; |
| 9 | + file?: string; |
| 10 | + alias?: string; |
| 11 | +} |
| 12 | + |
| 13 | +export class NgCliEnvironmentPlugin implements WebpackPlugin { |
| 14 | + _file: string; |
| 15 | + _alias: string; |
| 16 | + _env: string; |
| 17 | + |
| 18 | + constructor(config: any) { |
| 19 | + if (typeof config === 'string') { |
| 20 | + config = {env: config}; |
| 21 | + } |
| 22 | + if (typeof config.env !== 'string') { |
| 23 | + throw new Error('must provide env') |
| 24 | + } |
| 25 | + const ALIAS = { |
| 26 | + '"dev"': 'dev', |
| 27 | + 'development': 'dev', |
| 28 | + '"development"': 'dev', |
| 29 | + '"prod"': 'prod', |
| 30 | + 'production': 'prod', |
| 31 | + '"production"': 'prod', |
| 32 | + '"test"': 'test', |
| 33 | + 'testing': 'test', |
| 34 | + '"testing"': 'test', |
| 35 | + }; |
| 36 | + const ENV = config.env.toLowerCase(); |
| 37 | + |
| 38 | + this._file = config.file || 'environment'; |
| 39 | + this._alias = config.alias || ALIAS; |
| 40 | + this._env = this._alias[ENV] || ENV; |
| 41 | + } |
| 42 | + |
| 43 | + isEnvFile(file: string): boolean { |
| 44 | + return file.indexOf(this._file + '.') !== -1; |
| 45 | + } |
| 46 | + |
| 47 | + replaceFile(file: string): any { |
| 48 | + debugger; |
| 49 | + return file |
| 50 | + .replace(this._file, this._file + '.' + this._env); |
| 51 | + } |
| 52 | + |
| 53 | + updateResult(result: any): any { |
| 54 | + ['request', 'userRequest', 'resource'] |
| 55 | + .filter((key) => { return result[key]; }) |
| 56 | + .forEach((key) => { |
| 57 | + result[key] = this.replaceFile(result[key]); |
| 58 | + }); |
| 59 | + |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + apply(compiler: any): void { |
| 64 | + compiler.plugin('normal-module-factory', (normalModuleFactory: any) => { |
| 65 | + normalModuleFactory.plugin('after-resolve', (result, callback) => { |
| 66 | + var _resource = result['resource']; |
| 67 | + if (!this.isEnvFile(_resource)) { |
| 68 | + return callback(null, result); |
| 69 | + } |
| 70 | + debugger; |
| 71 | + var envFile = this.replaceFile(_resource); |
| 72 | + |
| 73 | + fs.stat(envFile, (err, stats) => { |
| 74 | + if (err || !stats.isFile()) { |
| 75 | + var errorText = (!err && stats.isFile()) ? 'Is not a file.' : 'Does not exist.'; |
| 76 | + console.log('\nWARNING:\n' + envFile + '\n' + errorText + ' ' + 'Using file\n' + _resource + '\n'); |
| 77 | + return callback(null, result); |
| 78 | + } |
| 79 | + // mutate result |
| 80 | + var newResult = this.updateResult(result); |
| 81 | + return callback(null, newResult); |
| 82 | + }); |
| 83 | + |
| 84 | + }); |
| 85 | + }); |
| 86 | + } |
| 87 | +} |
0 commit comments