[英]configuration file in javascriptservices react-redux template
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): 我知道这是一个非常常见的问题,而且我已经看到它在多个站点中多次回答,但是我无法使其正常工作。问题是我正在使用api和React组件(我正在使用打字稿2.4 .1和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. 我想自动检测应用程序在哪个环境中,并根据产品或开发者使用正确的API。
Searching through web I could manage to put this together in webpack.config: 通过网络搜索,我可以设法将其放到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"
). 通过这样调用fetch:
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. 我应该导入一些特定的东西来获取API_URL值。 I thought that API_URL would be globally accesible.
我认为API_URL将在全球范围内使用。 Any help would be very much appreciated.
任何帮助将不胜感激。
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. 该错误是因为Typescript编译器不知道webpack将提供
API_URL
,所以它实际上正在做得很好,并警告您使用的是不存在的变量。 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(/* ... */)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.