You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

gatsby-plugin-offline修改配置示例及配置适配问题咨询

Fixing gatsby-plugin-offline README Example Syntax Errors in gatsby-config.js

I get it—copy-pasting the default options from the plugin's README into your config file and hitting errors is super frustrating, especially when you already understand Service Workers but aren't deep into Gatsby's internals. Let's break down what's going wrong and fix it step by step.

Why the ${rootDir} Reference Breaks

The ${rootDir} in the README example is a documentation placeholder, not valid JavaScript syntax that Gatsby can interpret directly. Gatsby's gatsby-config.js is a standard Node.js module, so it doesn't recognize that template variable—it expects actual Node.js-compatible path references instead.

Fixing the Configuration

Here's how to adjust the example to work properly:

1. Replace ${rootDir} with Node.js's __dirname

__dirname is a built-in Node.js variable that points to the directory containing your gatsby-config.js file (which is almost always your project root). Swap out the placeholder with this variable, and the path will resolve correctly.

Modified config example:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-offline`,
      options: {
        workboxConfig: {
          globPatterns: [`${__dirname}/**/*.{html,js,css}`],
          // Add other custom Workbox options here as needed
        },
      },
    },
    // Your other plugins...
  ],
}

2. Adjust Paths if Your Config Isn't in the Root

If you've moved gatsby-config.js to a subfolder (like config/gatsby-config.js), you'll need to resolve the project root explicitly. First, require Node's path module at the top of your config, then use path.resolve() to climb up to the root:

const path = require('path');

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-offline`,
      options: {
        workboxConfig: {
          globPatterns: [`${path.resolve(__dirname, '../')}/**/*.{html,js,css}`],
        },
      },
    },
  ],
}

Testing the Fix

After updating the config:

  • Run gatsby build to generate the production build and Service Worker
  • Check the public/sw.js file in your project—you should see your custom glob patterns reflected in the caching rules
  • Test offline functionality by running gatsby serve and disabling your network connection in the browser dev tools

Bonus Tip: Start Simple

If you're still hitting issues, strip back the config to the plugin's defaults first to confirm it works without custom options:

module.exports = {
  plugins: [`gatsby-plugin-offline`],
}

Once that runs successfully, add back your custom Workbox options one at a time to isolate any other syntax issues.

内容的提问来源于stack exchange,提问作者capouch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:31:32