SyntaxError:意外的标记:punc())

时间:2017-04-01 21:32:08

标签: javascript reactjs redux uglifyjs

我收到了:

来自UglifyJS的

SyntaxError:意外的令牌:punc())

它指向全局变量API_URL的第一个字母。 我用这种方式实现了它:

export default reduxApi({
  campaigns: {
    url: `${API_URL}/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  } 
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})

如果我删除键url下的全局变量:

export default reduxApi({
  campaigns: {
    url: `/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  } 
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})

然后一切正常。有任何想法吗?为什么uglify会抛出那种错误?

2 个答案:

答案 0 :(得分:3)

Uglify并不完全支持ES6,template literals included。你可以track the conversation on Github。 ES6支持harmony branch。您可以通过将uglify的package.json条目替换为:

来使用该分支
"uglify-js": "git+https://github.com/mishoo/UglifyJS2.git#harmony"

或者,您可能希望在缩小之前首先通过转换器传递代码。这样,所有语法都将是ES5,Uglify非常了解它。如果您希望某些ES6语法保持不变,您可能需要调整您的转发器配置。

答案 1 :(得分:0)

我决定在这里写一个解决方案。我没有必要安装其他uglify-js软件包版本。重点是以适当的方式解决对象的导入问题。就我而言,API_URL是一个全局变量。所以Uglify不确定它是否已定义,这就是它抛出错误的原因。

为了解决这个问题,我以这种方式使用了webpack externals

// ------------------------------------                                                                                               
// Externals
// ------------------------------------
webpackConfig.externals = {
  config: JSON.stringify(require(`./${__DEV__ ? 'development' : 'production'}.json`)),                                                
}

它只是将JSON配置对象放入config变量,具体取决于环境(developmentproduction)。您需要做的就是将development.jsonproduction.json放在您定义webpackConfig.externals的文件旁边。

然后就像我的情况一样,你定义它让我们在development.json中说:

{
  "apiUrl": "http://localhost:5000"
}

然后最终在您的代码中:

... // other imports
import config from "config"

export default reduxApi({
  campaigns: {
    url: `${config.apiUrl}/api/v1/whatever`,
    transformer (response) {
      if (!response) return {}
      return response.data
    }
  } 
}).use('fetch', adapterFetch(fetch)).use('options', {
  headers: getRequestHeaders()
})

它就像一个魅力。

希望能帮助某人。

相关问题