Reputation: 231
I know this one is a very common question, and I have seen it being answered multiple times in multiple sites, but i could not manage to get it working The thing is I am consuming and api for a react component (I am using typescript 2.4.1 and webpack 2.5.1):
....
fetch("some/url/api/", method:"POST",...).then(/*some code*/)
I want to automatically detect in which environment the app is, and consume the right api depending if it's prod or dev.
Searching through web I could manage to put this together in webpack.config:
...
var API_URL = {
production: JSON.stringify('http://some.server.example'),
development: JSON.stringify('http://localhost:xxxx')
}
var environment = process.env.NODE_ENV === 'production'?'production':'development'
...
const sharedConfig = () =>({
...
plugins:[
...
new webpack.DefinePlugin({
'API_URL':API_URL[environment]
})
]
});
By calling fetch like this:
fetch(API_URL+"api/endpoint"
).
i got error saying:
Cannot find name 'API_URL'.any
Should I import something specific to get API_URL value. I thought that API_URL would be globally accesible. Any help would be very much appreciated.
Upvotes: 0
Views: 44
Reputation: 4522
This error is because typescript compiler is not aware that webpack will provide API_URL
, so it's actually doing its job great, and warning you that you are using a non existent variable. You know that the build will supply this though, so you can let it know that it exists by declaring it
first
declare const API_URL: string
//...
fetch(API_URL + "api/endpoint").then(/* ... */)
Upvotes: 0