Search code examples
vue-cliworkbox

How can I import other file in service worker file using workbox-webpack-plugin injectMode?


I am using vue-cli and workbox-webpack-plugin injectMode

new InjectManifest({
  swSrc: './src/sw.ts',
  swDest: 'sw.js',
}),

in sw.ts, I try to import other file

import { precacheAndRoute } from 'workbox-precaching'
import { registerRoute } from 'workbox-routing'
import { WorkboxPlugin, setCacheNameDetails, RouteHandler } from 'workbox-core'
import { CacheableResponsePlugin } from 'workbox-cacheable-response'
import { ExpirationPlugin } from 'workbox-expiration'
import Strategies, { CacheFirst, StaleWhileRevalidate } from 'workbox-strategies'

// import other file
import { CustomMessage, MessageType, MESSAGE_META, SWRouting } from './utils/registerSW'

but when building APP, it will fail,

error:  js/chunk-2d213953.a6b52dae.js from Terser
Unexpected token: punc (:) [js/chunk-2d213953.a6b52dae.js:3,12]

when I remove this import statment, building works well.

So, Could I import other files ? How ?


Solution

  • Generally speaking, what you're trying to do should work. The InjectManifest plugin will kick off a webpack child compilation for the your swSrc file, and will inherit whatever plugins and config you have set up for your main, parent compilation. It should be able to bundle ES modules into a final service worker.

    It sounds like there's something specific in one of those ./utils/registerSW imports that is causing Terser to be unable to parse the bundled code, though. I would recommend starting by just importing a very small, no-op function from ./utils/registerSW, and confirm that that works. Then try importing each of those functions from ./utils/registerSW one at a time until you find the one that's causing issues, and check the original source code to see what might be triggering it.

    It's possible that the child compilation kicked off by InjectManifest is misconfigured, and perhaps that's due to a bug that needs to be fixed, but I would start with those debugging steps first.