Gatsby에 Google 애널리틱스를 추가하는 방법

6099 단어 javascriptgatsby
Gatsby에 Google Analytics를 추가하는 것은 매우 쉽고 몇 분 안에 완료할 수 있습니다. Google Analytics를 추가하는 방법에는 두 가지가 있습니다.

가장 먼저 필요한 것은 Google Analytics 계정입니다. 계정 설정으로 시작하십시오HERE.

1. Google 애널리틱스에서 추적 ID 가져오기

After signing up for a Google Analytics account, create a property and get your tracking ID from the Tracking Code section under the Tracking Info menu. The tracking ID looks like this UA-12341234-1 .

2. 웹사이트 추적 추가

Now you have two options:

  • Install the official Google analytics plugin gatsby-plugin-google-gtag 또는
  • 사용자 정의에 추적 코드 추가html.js

  • 대부분의 경우 공식 플러그인이면 충분합니다. 이미 html.js를 사용자 정의한 경우(스크립트 삽입 등) 거기에 추적 코드를 추가할 수 있습니다.

    💰: Start your cloud journey with $100 in free credits with DigitalOcean!

    공식 플러그인을 통해 Google 애널리틱스 추가

    Install the plugin.

    npm install gatsby-plugin-google-gtag
    

    Add the plugin to your gatsby-config.js file:

    module.exports = {
      plugins: [
        // All other plugins
        {
          resolve: `gatsby-plugin-google-gtag`,
          options: {
            // You can add multiple tracking ids and a pageview event will be fired for all of them.
            trackingIds: [
              'ADD-YOUR-TRACKING-CODE-HERE', // Google Analytics / GA
              // optional
              'OPTIONAL----AW-CONVERSION_ID', // Google Ads / Adwords / AW
              'OPTIONAL----DC-FLOODIGHT_ID', // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager)
            ],
            // This object gets passed directly to the gtag config command
            // This config will be shared across all trackingIds
            gtagConfig: {
              optimize_id: 'OPT_CONTAINER_ID',
              anonymize_ip: true,
              cookie_expires: 0,
            },
            // This object is used for configuration specific to this plugin
            pluginConfig: {
              // Puts tracking script in the head instead of the body
              head: false,
              // Setting this parameter is also optional
              respectDNT: true,
              // Avoids sending pageview hits from custom paths
              exclude: ['/preview/**', '/do-not-track/me/too/'],
            },
          },
        },
      ],
    };
    
    All configuration options can be found in the plugin docs .

    html.js에 Google 애널리틱스 추가

    If you have already a html.js file, skip the next paragraph.

    Gatsby uses a React component to server render the <head> and other parts of the HTML outside of the core Gatsby application. Most sites should use the default html.js shipped with Gatsby and customizing html.js is not supported within a Gatsby Theme.

    If you need to insert custom HTML into the <head> or <footer> of each page on your site, you can use html.js.

    Copy the default html.js:

    cp .cache/default-html.js src/html.js
    

    Then add the website tracking code from Google Analytics:

    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=UA-12341234-1"
    />
    <script
      dangerouslySetInnerHTML={{
        __html: `
        window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
    
      gtag('config', 'UA-12341234-1');
      `,
      }}
    />
    

    IMPORTANT: I recommend using an environment variable to store your GA_TRACKING_ID .

    3. 빌드 및 테스트.

    The plugin only works in production mode. Hence, to test the correct firing of events run: gatsby build && gatsby serve . After deploying your website confirm that website tracking is working in Google Analytics.

    🎉🎉🎉 Congratulations! You have successfully added Google Analytics to your website. 🎉🎉🎉

    Thanks for reading and if you have any questions , use the comment function or send me a message .

    If you want to know more about Gatsby , 이것들을 보세요 Gatsby Tutorials .

    참조(큰 감사): Gatsby Docs

    좋은 웹페이지 즐겨찾기