Search code examples
angularangular-cliangular-module

Use environment to set proxy.config.js property for ng serve


Title pretty much sums it up. I've got a proxy.conf.js file that gets hit on ng serve and I just want to grab the target url from the environment ts file, or a json file, or I don't really care at this point, I just want one place to store the URL that feeds the others respectively...

So environment.congif.ts (which is not included in any configurations, just a file to store the settings object that currently feeds environment.dev.ts and is failing to feed proxy.conf.js);

export const environment = {
    production: false,
    apiUrl: 'http://localhost:12345'
};

Then proxy.conf.js;

var settings = require('./src/environments/environment.config');

const PROXY_CONFIG = [{
    "/restapi/*": {
      "target": settings.environment.apiUrl,
      "secure": false,
      "changeOrigin": true,
      "logLevel": "debug"
    }
}]

module.exports = PROXY_CONFIG

Which for some reason I obviously don't understand (especially since intellisense fills in the path just fine for both the file and the property) I get error on ng serve;

Cannot find module './src/environments/environment.config'
Error: Cannot find module './src/environments/environment.config'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
........

So my question is, why can it not resolve this way? I just want one file to set the target URL on that feeds the places it's needed from environment.config.ts

ADDENDUM : So the environment.*.ts files sit in /src/environments like with any default installation. The proxy.conf.js sits in the project root with other default files like package.json or angular.json. The paths are all correct, intellisense will even fill in the values but for whatever reason proxy.conf.js will not play nice when importing the const object from the environment (at build, though like I said intellisense finds everything just fine). So just like the title conveys, the only issue I'm having is reading the url into the proxy js file from the environment ts file so that I have only one file to maintain the apiurl in.


Solution

  • So the problem here turned out to be the version of typescript and its lack of import vs require support. If you're using anything like v3 you won't encounter the same issue. Thanks for looking!