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 -D

Note: 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存储库中的示例。