首页 > 解决方案 > 何不在开发中加载头脚本

问题描述

在我的 nuxt.config.js 中,我在 html 头配置中有一个脚本。

export default {
  // Target: https://go.nuxtjs.dev/config-target
  target: 'static',

  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'My cool Website !',
    script: [
      { 
        hid: "thesemetrics",
        src: "https://unpkg.com/thesemetrics@latest",
        async: true,
        type: "text/javascript",
     },
     { src: 'https://identity.netlify.com/v1/netlify-identity-widget.js'}
    ]
  },
  // ...
}

当我处于开发模式时,有没有办法不加载此脚本?

标签: vue.jsnuxt.js

解决方案


使用 的函数形式head,并基于 有条件地添加这些脚本process.env.NODE_ENV

export default {
  head() {
    const productionScripts =
      process.env.NODE_ENV === 'production'
        ? [
            { 
              hid: "thesemetrics",
              src: "https://unpkg.com/thesemetrics@latest",
              async: true,
              type: "text/javascript",
            },
            { src: 'https://identity.netlify.com/v1/netlify-identity-widget.js'}
          ]
        : []

    return {
      title: 'My cool Website !',
      script: [
        // other scripts to always load here

        ...productionScripts
      ]
    }
  },
  // ...
}

推荐阅读