我正在发布前端应用程序,我想跟踪(GA 和其他跟踪器)的统计信息。该应用程序是在 CI 上使用 webpack 预构建的,我希望将相同的包发送到暂存和生产环境。 但这有一个问题:如果我在构建期间启用跟踪器,它们将在两个环境中启用。
我看到的一种方法是在从服务器发送应用程序代码时在 index.html
中添加 set window.enableTrackers = true
标志,然后决定是否安装跟踪器,但这似乎是一个非常难看的解决方案。
你还有其他方法吗?也许在客户端检查域名?像这样的东西:
if(document.location.hostname === 'prod.example.com') {
// enable trackers
}
最佳答案
这最好在编译时通过为生产和阶段包配置不同的 Webpack 来解决,您可以在其中使用 CLI --define
或 --env
明确启用跟踪。
如果在编译时不解决包含tracking,那你就得借助其他手段了。一种选择是在运行时评估 GA 脚本是否应该加载到文档中。下面是一个 Rect 元素的示例,它仅在主机名与可配置的正则表达式匹配时才加载脚本:
import React, {Component, PropTypes} from 'react'
const production = new RegExp(RE_PRODUCTION_HOST)
export const ga = window.ga = window.ga || function () {
(ga.q = ga.q || []).push(arguments)
}
export class Analytics extends Component {
static propTypes = {
id: PropTypes.string.isRequired
};
componentDidMount () {
// Runtime evaluation for loading the GA script
if (!self.location.hostname.match(production)) {
return
}
const script = document.createElement('script')
script.src = 'https://www.google-analytics.com/analytics.js'
script.async = true
document.body.appendChild(script)
}
render () {
ga.l = +new Date()
ga('create', this.props.id, 'auto')
ga('send', 'pageview')
return null
}
}
在这里,我仍然可以安全地将 RE_PRODUCTION_HOST
定义为 production.com
甚至 ^(www.)?production.com%
我可以在测试编译期间更改它以做出断言。
另一种选择是添加 filters在 Google Analytics 中,它将根据主机名包含/排除结果。这不需要您对代码进行任何进一步的更改。
关于web - 当使用 webpack 预构建 Assets 时,仅为生产启用 GA 和其他跟踪器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40483910/