简体   繁体   English

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

[英]Service worker file can't find imported files

For this service worker I am working on I have managed to get it working but am now looking to expand upon it.对于我正在研究的这个服务人员,我已经设法让它工作,但现在正在寻求扩展它。 The idea would be for there to be separate mock data used dependant on whether it is the UK or US version of the website.这个想法是根据它是英国版还是美国版的网站,使用单独的模拟数据。

This is how it worked originally,原来是这样操作的

TestMode.ts:测试模式.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: 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>,
        );
    }
});

Now for expanding on this I have moved the mock data into another folder called mockServiceWorker, there is another one of these in the US folder as well.现在为了对此进行扩展,我已将模拟数据移动到另一个名为 mockServiceWorker 的文件夹中,在 US 文件夹中还有另一个文件夹。 The idea of this to import both the GB and US versions of the mock data and then from a check, the service worker will determine which data it should use.这样做的想法是导入模拟数据的 GB 和 US 版本,然后通过检查,Service Worker 将确定它应该使用哪些数据。

At the moment i am just trying to import the gb data and doing it like so:目前我只是想导入 gb 数据并这样做:

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

and now just trying to see it works by doing:现在只是想通过这样做来查看它的工作原理:

console.log(MOCK_DATA);

but whilst there are no errors in the workspace, in the terminal I am getting:但是虽然工作区中没有错误,但在终端中我得到:

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

Webpack is also used for this service worker. Webpack 也用于这个 service worker。 When the site is setup a worker.min.js file is generated in the dist folder and within there I am also getting the message:设置站点时,会在 dist 文件夹中生成一个 worker.min.js 文件,并且在其中我也收到以下消息:

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

I am at a loss as to why it cannot find the file.我不知道为什么它找不到文件。 Has anyone else experienced this and managed to fix it?有没有其他人经历过这个并设法解决它? Any help would be greatly appreciated任何帮助将不胜感激

In case anyone else has the same issue as me.以防其他人和我有同样的问题。 Check how your webpack config is setup, I had added a separate part to the config for the service worker and forgot ad:检查您的 webpack 配置是如何设置的,我在服务工作者的配置中添加了一个单独的部分并忘记了广告:

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

After adding this, I stopped getting the module not found errors.添加后,我停止收到未找到模块的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM