javascriptservices react-redux模板中的配置文件

时间:2018-01-15 16:32:45

标签: typescript webpack javascriptservices

我知道这是一个非常常见的问题,我已经看到它在多个站点中被多次回答,但我无法让它工作。事情是我正在消耗和api反应组件(我是使用typescript 2.4.1和webpack 2.5.1):

....
fetch("some/url/api/", method:"POST",...).then(/*some code*/)

我想自动检测应用程序在哪个环境中,并根据它的prod或dev消耗正确的api。

通过网络搜索我可以设法将它放在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]  
    })
  ]
});

通过这样调用fetch: fetch(API_URL+"api/endpoint")。 我得到错误说:

Cannot find name 'API_URL'.any

我应该导入特定的内容以获取API_URL值。我认为API_URL可以全局访问。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

此错误是因为typescript编译器不知道webpack将提供API_URL,因此它实际上正在完成其工作,并警告您正在使用不存在的变量。你知道构建将提供这个,所以你可以通过声明它让它知道它存在 第一

declare const API_URL: string
//...
fetch(API_URL + "api/endpoint").then(/* ... */)