I have come across this question many times on different platforms, but I haven't been able to make it work for me. The issue is that I am using an API within a React component (with TypeScript 2.4.1 and webpack 2.5.1):
....
fetch("some/url/api/", method:"POST",...).then(/*some code*/)
My goal is to automatically determine the environment of the app and fetch the correct api depending on whether it's in production or development mode.
After doing some research online, I put together the following code in my 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]
})
]
});
When I tried calling fetch like this:
fetch(API_URL+"api/endpoint"
),
I received the error message:
Cannot find name 'API_URL'.any
I am wondering if there is something specific I need to import to access the value of API_URL. I assumed it would be globally accessible. Any assistance on this matter would be greatly appreciated.