From 55513f0e3a5b8220623cd58c1a9f68d018408cd3 Mon Sep 17 00:00:00 2001 From: Kuitos Date: Fri, 11 Sep 2020 18:41:19 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20lazy=20init=20ScopedCSS=20to=20s?= =?UTF-8?q?upport=20referenced=20by=20html=20head=20script=20block=20(#923?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/sandbox/patchers/__tests__/css.test.ts | 12 +++++++++++- src/sandbox/patchers/css.ts | 17 ++++++++++++----- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/sandbox/patchers/__tests__/css.test.ts b/src/sandbox/patchers/__tests__/css.test.ts index e4e0b3c..7f5a657 100644 --- a/src/sandbox/patchers/__tests__/css.test.ts +++ b/src/sandbox/patchers/__tests__/css.test.ts @@ -3,9 +3,19 @@ * @since 2020-04-19 */ -import { processor as CSSProcessor } from '../css'; +import { ScopedCSS } from '../css'; import { sleep } from '../../../utils'; +let CSSProcessor: ScopedCSS; +beforeAll(() => { + CSSProcessor = new ScopedCSS(); +}); + +afterAll(() => { + // @ts-ignore + CSSProcessor = null; +}); + const fakeStyleNode = (css: string) => { const styleNode = document.createElement('style'); const textNode = document.createTextNode(css); diff --git a/src/sandbox/patchers/css.ts b/src/sandbox/patchers/css.ts index 5b93c86..1b97f6e 100644 --- a/src/sandbox/patchers/css.ts +++ b/src/sandbox/patchers/css.ts @@ -22,7 +22,7 @@ const arrayify = (list: CSSRuleList | any[]) => { return [].slice.call(list, 0) as T[]; }; -class ScopedCSS { +export class ScopedCSS { private static ModifiedTag = 'Symbol(style-modified-qiankun)'; private sheet: StyleSheet; @@ -174,10 +174,19 @@ class ScopedCSS { } } -const processor = new ScopedCSS(); +let processor: ScopedCSS; export const QiankunCSSRewriteAttr = 'data-qiankun'; -const process = (appWrapper: HTMLElement, stylesheetElement: HTMLStyleElement | HTMLLinkElement, appName: string) => { +export const process = ( + appWrapper: HTMLElement, + stylesheetElement: HTMLStyleElement | HTMLLinkElement, + appName: string, +) => { + // lazy singleton pattern + if (!processor) { + processor = new ScopedCSS(); + } + if (stylesheetElement.tagName === 'LINK') { console.warn('Feature: sandbox.experimentalStyleIsolation is not support for link element yet.'); } @@ -194,5 +203,3 @@ const process = (appWrapper: HTMLElement, stylesheetElement: HTMLStyleElement | processor.process(stylesheetElement, prefix); } }; - -export { process, processor };