通过 100+ 技巧学习 Nuxt!

partytown
@nuxtjs/partytown

Nuxt 的 Partytown 集成 - 将资源密集型脚本转移到 Web Worker 中,并从主线程中移出。

@nuxtjs/partytown

npm versionnpm downloadsGithub Actions CICodecovLicense

Partytown integration for Nuxt

特性

  • 👌 零配置要求
  • 🔥 将资源密集型脚本转移到 Web Worker 中
  • ⚡️ 加速你的网站
  • 💯 支持 Nuxt 3 和 Nuxt Bridge

快速设置

  1. 安装 @nuxtjs/partytown!
    npx nuxi@latest module add partytown
    
  2. 将其添加到 nuxt.config.tsmodules 部分
    export default defineNuxtConfig({
      modules: ['@nuxtjs/partytown'],
    })
    
  3. type: 'text/partytown' 属性添加到任何你想由 Partytown 处理的脚本。
    <template>
      <div>
        <Script type="text/partytown" src="https://example.com/analytics.js" />
      </div>
    </template>
    

配置

Partytown 支持许多选项,你可以在 nuxt.config.ts 文件中传递这些选项

export default defineNuxtConfig({
  // ...
  partytown: {
    /**
     * When `true`, Partytown scripts are not minified. See https://partytown.builder.io/configuration
     * on how to enable more logging.
     *
     * @default true in development
     */
    debug: boolean
    /**
     * Path (relative to your base URL) where the Partytown library should be served from.
     *
     * @default '~partytown'
     */
    lib: string
    // For other options, see https://partytown.builder.io/configuration
  },
})

配置示例

Crisp

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['$crisp', '$crisp.push'],
  },
  app: {
    head: {
      script: [
        // Insert your CRISP Script here e.g.:
        { innerHTML: 'window.$crisp = []; window.CRISP_WEBSITE_ID = "0000"' },
        { src: 'https://client.crisp.chat/l.js', async: true, type: 'text/partytown' },
      ],
    },
  },
})

Google Tag Manager

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['dataLayer.push'],
  },
  app: {
    head: {
      script: [
        // Insert your Google Tag Manager Script here
        { src: '-', async: true, type: 'text/partytown' },
      ],
    },
  },
})

Plausible Analytics

export default defineNuxtConfig({
  modules: ['@nuxtjs/partytown'],
  partytown: {
    forward: ['$plausible', '$plausible.push'],
  },
  app: {
    head: {
      script: [
        { innerHTML: 'window.$plausible = [];' },
        // Update this
        {
          src: 'https://127.0.0.1/js/script.js',
          defer: true,
          type: 'text/partytown',
          'data-domain': 'your-domains',
        },
      ],
    },
  },
})

开发

  • 运行 yarn prepare 以生成类型存根。
  • 使用 yarn dev 在开发模式下启动 playground

许可

MIT 许可