webpack 谷歌地图_如何在Webpack中设置可靠且可维护的Google Analytics(分析)
webpack 谷歌地圖
One of the messier bits of a new app setup is trying to figure out where to stash your Google Analytics initialization scripts. There are some existing options like React Helmet to manage the head of your document. You can toss it in your monolithic index.html file.
新應用設置中比較混亂的部分之一是試圖弄清楚將Google Analytics(分析)初始化腳本存放在哪里。 有一些現有的選項,例如React Helmet,可以管理文檔的頭部。 您可以將其放入您的整體index.html文件中。
The thing is, those setups rarely work out the way you want them to. They end up as ugly blocks of HTML strings in your JavaScript. You end up having to manage that monolith of an index.html file I mentioned before throughout your project’s lifecycle.
關鍵是,這些設置很少能按您希望的方式進行。 它們最終變成JavaScript中HTML字符串的丑陋塊。 您最終不得不管理我在整個項目生命周期中提到的index.html文件的整體。
為什么這很重要 (Why this matters)
Beyond how you manage your code, if analytics is crucial to you and your business, you want to make sure the setup is reliable and correctly installed.
除了管理代碼之外,如果分析對您和您的業務至關重要,您還需要確保設置可靠并正確安裝。
Many developers assume that because it’s a JS snippet, the best practice is to toss it at the bottom of the page. The issue with this is that throwing it at the end leaves a higher risk that you’ll miss tracking a hit before a user exits the page, as Analytics won’t initialize until the rest of the page loads. That’s why Google itself recommends installing the snippet as high in the head as possible.
許多開發人員認為,因為它是JS代碼段,所以最佳實踐是將其放在頁面底部。 這樣做的問題是,將其扔到最后會帶來較高的風險,您會錯過在用戶退出頁面之前跟蹤匹配的風險,因為Analytics(分析)會在頁面其余部分加載之前不會進行初始化。 這就是Google本身建議將代碼段安裝在盡可能高的頭部的原因 。
As important as I say this is, you might not care as much if you’re more relaxed about it and want to get a general idea about how things are running on your portfolio site. However, if you expand your reach into other tools like A/B testing with Google Optimize, it’s even more critical to have GA recognize the page and the experiment running to avoid additional delays or worse, page flickering. ?
就像我所說的那樣重要,如果您對它不那么放松,并且想要對投資組合網站上的運行情況有一個總體了解,那么您可能不太在意。 但是,如果您將其覆蓋面擴展到其他工具(例如使用Google Optimize進行A / B測試),則讓GA識別頁面和正在運行的實驗來避免額外的延遲或更糟的頁面閃爍就顯得尤為重要。 ?
我們如何解決這個問題 (How we’ll fix this)
Partials for HTML Webpack Plugin is an extension of HTML Webpack Plugin that simplifies your partial management. Its goal is to specifically try to avoid the practice of maintaining an index.html file in Webpack projects and instead defer to maintainable partials simplifying your setup.
HTML Webpack插件的部分內容是HTML Webpack插件的擴展,可簡化您的部分管理。 它的目標是專門嘗試避免在Webpack項目中維護index.html文件的做法,而是遵從可維護的部分來簡化設置。
For now, we’re going to focus on getting Google Analytics set up, but I recommend checking out Google Tag Manager for managing tags generally, which I’ll cover later in a followup post.
目前,我們將重點放在設置Google Analytics(分析)上,但是我建議您檢出Google跟蹤代碼管理器以全面管理代碼,稍后將在后續文章中介紹。
TL;DR — If you want to jump straight to the solution, you can grab the code here.
TL; DR —如果您想直接跳到解決方案, 可以在此處獲取代碼 。
入門 (Getting started)
We’ll want to start out with a basic Webpack setup with HTML Webpack Plugin already configured. This guide won’t walk you through that setup, but here are a couple of starting points if you’re not familiar:
我們將首先從基本Webpack設置開始,并已配置HTML Webpack插件。 本指南不會引導您完成該設置,但是如果您不熟悉,這里有一些起點:
Webpack’s Getting Started guide
Webpack入門指南
Webpack’s guide for HTML Webpack Plugin
WebpackHTML Webpack插件指南
A ton of excellent tutorials out there you can find by Googling around a little bit
您可以通過谷歌搜索找到大量優秀的教程
Lastly, if you already have an index.html set up, I won’t judge you for now, but hopefully this inspires you to approach other snippets the same way and remove the need for a managed index.html file at all.
最后,如果您已經設置了index.html ,那么我暫時不會評判您,但是希望這能激發您以相同的方式處理其他代碼片段,并完全不需要托管的index.html文件。
為HTML Webpack插件安裝Partials (Installing Partials for HTML Webpack Plugin)
Once you already have your basic setup and HTML Webpack Plugin installed, our Partials plugin is an easy add:
一旦您已經完成基本設置并安裝了HTML Webpack插件,便可以輕松添加我們的Partials插件:
yarn add html-webpack-partials-plugin -DNote: make sure to properly set up the package dependency based on your project configuration.
注意:請確保根據您的項目配置正確設置軟件包依賴項。
設置您的部分 (Set up your partial)
Next, we’ll want to create our partial. My preference for generally managing them is to create a new directory called partials in the source root. For example, if your entry point lives at src/main.js, your partials directory would be right next to it at src/partials.
接下來,我們要創建我們的局部視圖。 我通常希望對它們進行管理是在源根目錄中創建一個稱為“ partials的新目錄。 例如,如果您的入口點位于src/main.js ,則您的partials目錄將位于src/partials旁邊。
Once you have your preferred location, let’s create an analytics.html file in our new partials directory. For now, let’s throw in some test code, so we know it works. In analytics.html:
確定您的首選位置后,讓我們在新的partials目錄中創建analytics.html文件。 現在,讓我們添加一些測試代碼,以便我們知道它可以工作。 在analytics.html :
<style> body { background-color: #5F4B8B; } </style>配置您的部分 (Configure your partial)
Open up your webpack.config.js and let’s set up the partial to get included in our build.
打開您的webpack.config.js然后設置要包含在我們的構建中的partial。
First, require the plugin at the top of your config. In webpack.config.js:
首先,要求插件位于您的配置頂部。 在webpack.config.js :
const HtmlWebpackPartialsPlugin = require('html-webpack-partials-plugin');Next, and this is very important, include a new instance of the plugin AFTER your instance of HtmlWebpackPlugin(). In the plugins section of webpack.config.js:
接下來,這非常重要,在HtmlWebpackPlugin()實例之后添加一個新的插件實例。 在webpack.config.js的插件部分中:
... plugins: [new HtmlWebpackPlugin(),new HtmlWebpackPartialsPlugin({path: './path/to/src/partials/analytics.html'),location: 'head',priority: 'high'}) ...Now let’s first break down that config before moving on:
現在讓我們先分解該配置,然后繼續:
path: this is what it sounds like, the path to the partial file in our project. Make sure to update this to the right location so the plugin can find it.
path :這聽起來像是我們項目中部分文件的路徑。 確保將其更新到正確的位置,以便插件可以找到它。
location: the HTML tag the plugin looks for.
location :插件尋找HTML標簽。
priority: this determines whether at compile time, our plugin adds our partial at the beginning of the specified location tag or the end (opening vs. closing).
優先級 :這決定了在編譯時,我們的插件是在指定location標記的開始還是結尾(開始還是結束)添加我們的partial。
Like we covered earlier, we want to add this as high in the <head> as possible. For most HTML tags used in location, Partials add it right after the opening tag if the priority is high. But with the <head> tag, Partials looks for your charset meta tag and injects it immediately after, as it’s important to render that in the document first.
就像我們之前介紹的一樣,我們希望將其盡可能地添加到<he ad>中。 對于大多數HTML標簽我們ed in lo陽離子,局部模板開始標記,如果先驗后立即將其添加ty i的高。 但是h the <head>標記,Partials會ks for您的charset meta標記,并在之后立即將其注入,因為首先將其呈現在文檔中很重要。
測試一下 (Test it out)
Compile Webpack, open your project in your browser, and you should now see a nice, ultraviolet background. ?
編譯Webpack,在瀏覽器中打開項目,您現在應該會看到漂亮的紫外線背景。 ?
If you take a look at the source, you should see the snippet get added right after the charset tag!
如果您查看源代碼,應該會在charset標簽之后立即添加該代碼段!
現在開始分析 (Now to Analytics)
Let’s update our analytics.html file to look something like this:
讓我們更新我們的analytics.html文件,使其看起來像這樣:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-XXXXXXXX-X'); </script>Just make sure to update the IDs (UA-XXXXXXXX-X) to your match your Google Analytics property value. Your Analytics snippet may also vary depending on your setup.
只需確保將ID( UA-XXXXXXXX-X )更新為與您的Google Analytics(分析)媒體資源值匹配的ID即可。 您的Google Analytics(分析)代碼段也可能會有所不同,具體取決于您的設置。
You should now be able to recompile Webpack and see your page start to ping Google Analytics! ?
現在,您應該能夠重新編譯Webpack,并看到您的頁面開始ping Google Analytics(分析)! ?
Note: you might have to load your project file from a server before GA is recognized rather than straight off of your local filesystem
注意:您可能必須先從服務器加載項目文件,然后才能識別出GA,而不是直接從本地文件系統
讓我們更進一步 (Let’s take it a step further)
This is great and all, but when dealing with Google Analytics, it’s nice to have a few different properties, such as one for development and one for production. This helps avoid polluting the production property with data from your development team (or you) poking around the application.
一切都很好,但是與Google Analytics(分析)打交道時,最好擁有一些不同的屬性,例如一個用于開發,一個用于生產。 這有助于避免使用開發團隊(或您)在應用程序中四處瀏覽的數據污染生產屬性。
設置局部變量 (Setting up partial variables)
Let’s go back to our webpack.config.js file and set up a variable to pass our property ID in:
讓我們回到webpack.config.js文件,并設置一個變量以在以下位置傳遞屬性ID:
... plugins: [new HtmlWebpackPlugin(),new HtmlWebpackPartialsPlugin({path: './path/to/src/partials/analytics.html'),location: 'head',priority: 'high',options: {ga_property_id: 'UA-XXXXXXXX-X'}}) ...Next, update your analytics.html file to recognize this value. Similar to HTML Webpack Plugin, Partials uses Lodash templating to make this work. In analytics.html:
接下來,更新您的analytics.html文件以識別該值。 與HTML Webpack插件類似,Partials使用Lodash模板來完成這項工作。 在analytics.html :
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= ga_property_id %>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '<%= ga_property_id %>'); </script>Now compile again and profit!
現在再次編譯并獲利!
To verify your tag is appropriately set up, I recommend checking out Google Tag Assistant available on Chrome.
為了驗證您的標簽設置正確,建議您查看Chrome上可用的Google Tag Assistant 。
為不同的媒體資源ID進行設置 (Setting this up for different property IDs)
From here, you have a few options as to how you manage your different property IDs. You can:
在這里,您可以選擇一些方法來管理不同的媒體資源ID。 您可以:
Set up separate development and production Webpack configs
設置單獨的開發和生產Webpack配置
Create an environment config (ex: env.config.js) that allows you to import the settings
創建一個環境配置(例如: env.config.js ),以允許您導入設置
- Both (recommended) 兩者(推薦)
Setting it up this way will give you the opportunity to run the properties dynamically between your local development and production builds. Just remember not to store your env file in git if you’re going to add sensitive data. ?
以這種方式進行設置將使您有機會在本地開發和生產版本之間動態運行屬性。 請記住,如果要添加敏感數據,請不要在git中存儲環境文件。 ?
那么,我們從中得到什么呢? (So what are we getting out of this?)
The ideal scenario is you take this and run with it for the rest of your HTML living in index.html. This helps split your code up into more manageable pieces and lets Webpack generate the file for you rather than you trying to override and manage it yourself.
理想的情況是,您可以將它放在index.html ,然后將其用于其余HTML。 這有助于將您的代碼分成更易于管理的部分,并使Webpack為您生成文件,而不是您嘗試覆蓋和管理它。
Specifically for Google Analytics, we have a few benefits:
專門針對Google Analytics(分析),我們有一些好處:
- Ensuring the snippet is loading in a reliable location 確保代碼段加載在可靠的位置
- Providing a more reasonable way to maintain the snippet itself 提供更合理的方式來維護代碼片段本身
- Managing your property ID through your Webpack config 通過Webpack配置管理您的媒體資源ID
- And bonus: loading it as an env variable through your Webpack config 額外的好處:通過Webpack配置將其作為環境變量加載
To see the full solution with some example code, check out the example in the GitHub repo.
要查看帶有一些示例代碼的完整解決方案, 請查看GitHub存儲庫中的示例。
🐦 Follow Me On Twitter
Twitter在Twitter上關注我
📽? Subscribe To My Youtube
Subscribe?訂閱我的YouTube
?? Sign Up For My Newsletter
??注冊我的時事通訊
Originally published at https://www.colbyfayock.com/2018/08/reliable-and-maintainable-google-analytics-in-webpack.
最初發布在https://www.colbyfayock.com/2018/08/reliable-and-maintainable-google-analytics-in-webpack中 。
翻譯自: https://www.freecodecamp.org/news/how-to-set-up-reliable-and-maintainable-google-analytics-in-webpack-6b68bfde29b3/
webpack 谷歌地圖
總結
以上是生活随笔為你收集整理的webpack 谷歌地图_如何在Webpack中设置可靠且可维护的Google Analytics(分析)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到拔竹笋是什么意思
- 下一篇: react避免子组件渲染_如何与Reac