微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Service Worker 文件找不到导入的文件

如何解决Service Worker 文件找不到导入的文件

对于我正在处理的这个 Service Worker,我已经设法让它工作,但现在正在寻求扩展它。这个想法是根据网站是英国版还是美国版使用单独的模拟数据。

原来是这样的,

TestMode.ts:

class TestMode {
    constructor() {
        if (!this.isEnabled()) {
            return;
        }

        if (!('serviceWorker' in navigator)) {
            // eslint-disable-next-line no-console
            console.log('browser does not support service workers');
            return;
        }

        this.init();
    }

    private init(): void {
        navigator.serviceWorker
            .register('worker.min.js')
            .then(this.handleRegistration)
            .catch((error) => {
                throw new Error('Service Worker registration Failed: ' + error.message);
            });
    }

    private handleRegistration(registration: ServiceWorkerRegistration): void {
        registration.update();

        // eslint-disable-next-line no-console
        console.log('Registration successful,scope is:',registration.scope);

    }

    private isEnabled(): boolean {
        return locationService.hasParam('testMode');
    }
}

export default new TestMode();

serviceWorker.ts:

// eslint-disable-next-line spaced-comment
/// <reference lib="WebWorker" />

// export empty type because of tsc --isolatedModules flag

export type {};
declare const self: ServiceWorkerGlobalScope;

const CACHE_NAME = 'mockData-cache';


const MOCK_DATA_RECORD: Record<string,string> = {
    '/units/all?availability=Active&roomTypeHandle=kitchens': 'mock-data/unitData.json','/frontal-ranges/kitchens?': 'mock-data/kitchensData.json','/carcase-ranges/?availability=Active&roomTypeHandle=kitchens': 'mock-data/carcaseRangesData.json','/products/830368/related?roomTypeHandle=kitchens&productStateHandle=Active&limit=1000&campaignPhaseId=183&retailStore=Finishing%20touches%20%28Extra%29': 'mock-data/relatedItems.json','/carcase-placeholders?productStateHandle=Active&carcaseRangeHandle=Feature%20Bianco%20Grain&limit=1000&roomTypeId=1': 'mock-data/carcasePlaceholdersBiancoData.json','/frontal-placeholders?productStateHandle=Active&frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&limit=1000&roomTypeId=1': 'mock-data/frontalPlaceholdersActive.json','/frontal-placeholders?productStateHandle%5B0%5D=Active&productStateHandle%5B1%5D=SemiRetired&frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&limit=1000&roomTypeId=1':
        'mock-data/frontalPlaceholdeRSSemiRetired.json','/carcase-placeholders?productStateHandle=Active&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&limit=1000&roomTypeId=1': 'mock-data/carcasePlaceholdersActive.json','/api/json/unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Base&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/unitRangeBase.json','/api/json/unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Wall&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/unitRangeWall.json','/api/json/unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Tower&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/unitRangetower.json','/api/json/unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Island&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/unitRangeIsland.json','/api/json/feature-unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Base&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/featureUnitRangeBase.json','/api/json/feature-unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Wall&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/featureUnitRangeWall.json','/api/json/feature-unit-range-deFinitions?frontalRangeHandle=Infinity%20Plus%20Milano-Ultra%20Bianco%20Gloss&carcaseRangeHandle=Infinity%20Plus%20Milano%20White%20Edged&drawerBoxrangeHandle=Infinity%20Plus%20Glass%20Drawer%20Box&unitTypes=Island&orderPromotionId=183&roomTypeHandle=kitchens':
        'mock-data/featureUnitRangeIsland.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&selectedCollection=Infinity%20Plus%20Milano&retailSubCategory.handle=Timber&productMaterial.name=Timber':
        'mock-data/productsWorktopsTimber.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&selectedCollection=Infinity%20Plus%20Milano&retailSubCategory.handle=Bespoke&productMaterial.name=Luxury%20Laminate':
        'mock-data/productsWorktopsLuxuryLaminate.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&selectedCollection=Infinity%20Plus%20Milano&retailSubCategory.handle=Laminate&productMaterial.name=Laminate':
        'mock-data/productsWorktopsLaminate.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&selectedCollection=Infinity%20Plus%20Milano&retailSubCategory.handle=K-Life&productMaterial.name=K-Life':
        'mock-data/productsWorktopsKLife.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&selectedCollection=Infinity%20Plus%20Milano&retailSubCategory.handle=Bespoke&productMaterial.name=Luxury%20Bespoke':
        'mock-data/productsWorktopsLuxuryBespoke.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&selectedCollection=Infinity%20Plus%20Milano&retailSubCategory.handle=Bespoke&productMaterial.name=Rhino%20Edge':
        'mock-data/productsWorktopsRhinoEdge.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1000&campaignPhaseId=183&productId%5B0%5D=1003558&productId%5B1%5D=1003544': 'mock-data/productsProductID1003544.json','/products?roomTypeHandle=kitchens&productStateHandle%5B0%5D=Active&productStateHandle%5B1%5D=Inactive&productStateHandle%5B2%5D=EndOfLife&productStateHandle%5B3%5D=Dead&limit=1000&campaignPhaseId=183&retailSubCategory.handle%5B0%5D=Milanoprofiles&retailSubCategory.handle%5B1%5D=BasetopProfile':
        'mock-data/productsBasetopProfile.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&attributes.Worktop%20Type=Worktop%2CBreakfast%20Bar&productMaterial.name=Luxury%20Laminate&selectedCollection=Infinity%20Plus%20Milano&groupBy=plannerColour.name':
        'mock-data/productsWorktopsLuxuryLaminatePlannerColour.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1&campaignPhaseId=183&retailCategory.handle=Worktops&productMaterial.name=Luxury%20Laminate&plannerColour.name=Aleve&groupBy=edgeColour.name&selectedCollection=Infinity%20Plus%20Milano':
        'mock-data/productsWorktopsLuxuryLaminatePlannerColourAleve.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1000&campaignPhaseId=183&retailCategory.handle=Lighting': 'mock-data/productsLighting.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1000&campaignPhaseId=183&productId%5B0%5D=830368': 'mock-data/productsActiveProductID830368.json','/products?productId=830368&campaignPhaseId=183&roomTypeHandle=kitchens': 'mock-data/productsProductID830368.json','/products?roomTypeHandle=kitchens&productStateHandle=Active&limit=1000&campaignPhaseId=183&retailCategory.handle=Milanoprofiles&productColour.name=Camel':
        'mock-data/productsCamel.json','/products/830368/related?roomTypeHandle=kitchens&productStateHandle=Active&limit=1000&campaignPhaseId=183&selectedCollection=Infinity%20Plus%20Milano&retailStore=Finishing%20touches%20%28Extra%29':
        'mock-data/relatedItemsInfinityPlusMilano.json','/products?roomTypeHandle=kitchens&productStateHandle%5B0%5D=Active&productStateHandle%5B1%5D=SemiRetired&limit=1000&campaignPhaseId=183&productId%5B0%5D=830368':
        'mock-data/productsSemiRetiredData.json',};


self.addEventListener('install',(event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                return cache.addAll(Object.values(MOCK_DATA_RECORD));
            }),);
    self.skipwaiting();
});

self.addEventListener('activate',function () {
    return self.clients.claim();
});

self.addEventListener('fetch',(event) => {
    const url = new URL(event.request.url);
    const pathAndQuery = url.pathname + url.search;

    if (pathAndQuery in MOCK_DATA_RECORD) {
        const cacheKey = MOCK_DATA_RECORD[pathAndQuery];

        event.respondWith(
            caches.match(cacheKey,{
                cacheName: CACHE_NAME,}) as Promise<Response>,);
    }
});

现在为了扩展这一点,我已将模拟数据移动到另一个名为 mockServiceWorker 的文件夹中,其中在 US 文件夹中还有另一个。这个想法是导入 GB 和 US 版本的模拟数据,然后通过检查,Service Worker 将确定它应该使用哪些数据。

目前我只是想导入 gb 数据并这样做:

import { MOCK_DATA } from './mockServiceWorker/mockData';

现在只是尝试通过执行以下操作来查看它的效果

console.log(MOCK_DATA);

虽然工作区中没有错误,但在终端中我得到了:

Module not found: Error: Can't resolve './mockServiceWorker/mockData' in '/Users/lewis.ross/git/planner2d/core'

Webpack 也用于此 Service Worker。当站点设置好后,会在 dist 文件夹中生成一个 worker.min.js 文件,在那里我也收到消息:

function webpackMissingModule() { var e = new Error("Cannot find module './mockServiceWorker/mockData 

我不知道为什么找不到文件。有没有其他人经历过这个并设法解决它?任何帮助将不胜感激

解决方法

如果其他人有和我一样的问题。检查你的 webpack 配置是如何设置的,我已经为 service worker 的配置添加了一个单独的部分,但忘记了广告:

resolve: {
    extensions: ['.js','.jsx','.ts','.tsx','.json','.hbs'],modules: [
        COUNTRY_CODE_PATH,],alias: ALIAS_MAIN,},

添加此内容后,我不再收到找不到模块的错误。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。