@tiny-codes/vite-plugin-qiankun 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @tiny-codes/vite-plugin-qiankun
2
2
 
3
+ ## v2.0.2
4
+
5
+ 2024-4-3
6
+
7
+ ### Features
8
+
9
+ - Enhance module preloading to support cross-origin.
10
+ - Add `qiankun:loaded` event to notify when micro app is fully loaded.
11
+ - Add `qiankun:fetchEntryError` event to notify when fetching the entry script fails.
12
+ - Add `qiankun:runtimeError` event to notify when a runtime error occurs.
13
+
14
+ ## v2.0.1
15
+
16
+ 2024-4-2
17
+
18
+ ### Features
19
+
20
+ - Support `development` mode by default without any configuration.
21
+
3
22
  ## v2.0.0
4
23
 
5
24
  2024-4-1
package/es/helper.d.ts CHANGED
@@ -3,15 +3,16 @@ export interface QiankunProps {
3
3
  [x: string]: unknown;
4
4
  }
5
5
  export interface QiankunLifeCycle {
6
- bootstrap: (props?: QiankunProps) => void | Promise<void>;
7
- mount: (props: QiankunProps) => void | Promise<void>;
8
- unmount: (props: QiankunProps) => void | Promise<void>;
9
- update: (props: QiankunProps) => void | Promise<void>;
6
+ bootstrap?: (props?: QiankunProps) => void | Promise<void>;
7
+ mount?: (props: QiankunProps) => void | Promise<void>;
8
+ unmount?: (props: QiankunProps) => void | Promise<void>;
9
+ update?: (props: QiankunProps) => void | Promise<void>;
10
10
  }
11
11
  export interface QiankunWindow {
12
12
  __POWERED_BY_QIANKUN__?: boolean;
13
+ __INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
14
+ qiankunLifeCycles?: QiankunLifeCycle;
13
15
  [x: string]: any;
14
16
  }
15
17
  export declare const qiankunWindow: QiankunWindow;
16
- export declare const renderWithQiankun: (qiankunLifeCycle: QiankunLifeCycle) => void;
17
- export default renderWithQiankun;
18
+ export declare const exportQiankunLifeCycles: (qiankunLifeCycle: QiankunLifeCycle) => void;
package/es/helper.js CHANGED
@@ -1,14 +1,9 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1
2
  export var qiankunWindow = typeof window !== 'undefined' ? window.proxy || window : {};
2
- export var renderWithQiankun = function renderWithQiankun(qiankunLifeCycle) {
3
- // 函数只有一次执行机会,需要把生命周期赋值给全局
3
+ export var exportQiankunLifeCycles = function exportQiankunLifeCycles(qiankunLifeCycle) {
4
+ // The function has only one chance to execute, and the lifecycle needs to be assigned to the global scope.
4
5
  if (qiankunWindow !== null && qiankunWindow !== void 0 && qiankunWindow.__POWERED_BY_QIANKUN__) {
5
- if (!window.moudleQiankunAppLifeCycles) {
6
- window.moudleQiankunAppLifeCycles = {};
7
- }
8
- if (qiankunWindow.qiankunName) {
9
- window.moudleQiankunAppLifeCycles[qiankunWindow.qiankunName] = qiankunLifeCycle;
10
- }
6
+ qiankunWindow.qiankunLifeCycles = qiankunLifeCycle;
11
7
  }
12
8
  };
13
- export default renderWithQiankun;
14
9
  //# sourceMappingURL=helper.js.map
package/es/helper.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["qiankunWindow","window","proxy","renderWithQiankun","qiankunLifeCycle","__POWERED_BY_QIANKUN__","moudleQiankunAppLifeCycles","qiankunName"],"sources":["../src/helper.ts"],"sourcesContent":["export interface QiankunProps {\n container?: HTMLElement;\n [x: string]: unknown;\n}\n\nexport interface QiankunLifeCycle {\n bootstrap: (props?: QiankunProps) => void | Promise<void>;\n mount: (props: QiankunProps) => void | Promise<void>;\n unmount: (props: QiankunProps) => void | Promise<void>;\n update: (props: QiankunProps) => void | Promise<void>;\n}\n\nexport interface QiankunWindow {\n __POWERED_BY_QIANKUN__?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any;\n}\n\nexport const qiankunWindow: QiankunWindow = typeof window !== 'undefined' ? window.proxy || window : {};\n\nexport const renderWithQiankun = (qiankunLifeCycle: QiankunLifeCycle) => {\n // 函数只有一次执行机会,需要把生命周期赋值给全局\n if (qiankunWindow?.__POWERED_BY_QIANKUN__) {\n if (!window.moudleQiankunAppLifeCycles) {\n window.moudleQiankunAppLifeCycles = {};\n }\n if (qiankunWindow.qiankunName) {\n window.moudleQiankunAppLifeCycles[qiankunWindow.qiankunName] = qiankunLifeCycle;\n }\n }\n};\n\nexport default renderWithQiankun;\n"],"mappings":"AAkBA,OAAO,IAAMA,aAA4B,GAAG,OAAOC,MAAM,KAAK,WAAW,GAAGA,MAAM,CAACC,KAAK,IAAID,MAAM,GAAG,CAAC,CAAC;AAEvG,OAAO,IAAME,iBAAiB,GAAG,SAApBA,iBAAiBA,CAAIC,gBAAkC,EAAK;EACvE;EACA,IAAIJ,aAAa,aAAbA,aAAa,eAAbA,aAAa,CAAEK,sBAAsB,EAAE;IACzC,IAAI,CAACJ,MAAM,CAACK,0BAA0B,EAAE;MACtCL,MAAM,CAACK,0BAA0B,GAAG,CAAC,CAAC;IACxC;IACA,IAAIN,aAAa,CAACO,WAAW,EAAE;MAC7BN,MAAM,CAACK,0BAA0B,CAACN,aAAa,CAACO,WAAW,CAAC,GAAGH,gBAAgB;IACjF;EACF;AACF,CAAC;AAED,eAAeD,iBAAiB"}
1
+ {"version":3,"names":["qiankunWindow","window","proxy","exportQiankunLifeCycles","qiankunLifeCycle","__POWERED_BY_QIANKUN__","qiankunLifeCycles"],"sources":["../src/helper.ts"],"sourcesContent":["export interface QiankunProps {\n container?: HTMLElement;\n [x: string]: unknown;\n}\n\nexport interface QiankunLifeCycle {\n bootstrap?: (props?: QiankunProps) => void | Promise<void>;\n mount?: (props: QiankunProps) => void | Promise<void>;\n unmount?: (props: QiankunProps) => void | Promise<void>;\n update?: (props: QiankunProps) => void | Promise<void>;\n}\n\nexport interface QiankunWindow {\n __POWERED_BY_QIANKUN__?: boolean;\n __INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;\n qiankunLifeCycles?: QiankunLifeCycle;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const qiankunWindow: QiankunWindow = typeof window !== 'undefined' ? (window as any).proxy || window : {};\n\nexport const exportQiankunLifeCycles = (qiankunLifeCycle: QiankunLifeCycle) => {\n // The function has only one chance to execute, and the lifecycle needs to be assigned to the global scope.\n if (qiankunWindow?.__POWERED_BY_QIANKUN__) {\n qiankunWindow.qiankunLifeCycles = qiankunLifeCycle;\n }\n};\n"],"mappings":"AAoBA;AACA,OAAO,IAAMA,aAA4B,GAAG,OAAOC,MAAM,KAAK,WAAW,GAAIA,MAAM,CAASC,KAAK,IAAID,MAAM,GAAG,CAAC,CAAC;AAEhH,OAAO,IAAME,uBAAuB,GAAG,SAA1BA,uBAAuBA,CAAIC,gBAAkC,EAAK;EAC7E;EACA,IAAIJ,aAAa,aAAbA,aAAa,eAAbA,aAAa,CAAEK,sBAAsB,EAAE;IACzCL,aAAa,CAACM,iBAAiB,GAAGF,gBAAgB;EACpD;AACF,CAAC"}
package/es/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { load } from 'cheerio';
2
- import { detectIndent, space } from "./utils";
2
+ import { detectIndent, normalizeUrl, space } from "./utils";
3
3
  export * from "./helper";
4
4
  /**
5
5
  * Vite plugin for integrating with Qiankun micro frontend.
@@ -23,28 +23,77 @@ var qiankunPlugin = function qiankunPlugin(appName) {
23
23
  var $ = load(html, {
24
24
  sourceCodeLocationInfo: true
25
25
  });
26
+ // Transform entry script
26
27
  var entryScript = (_$$get = $('script[entry]').get(0)) !== null && _$$get !== void 0 ? _$$get : $('body script[type=module], head script[crossorigin=""]').get(0);
27
28
  if (entryScript) {
28
- var _script$$html;
29
+ var _script$$html, _context$server;
30
+ var url = entryScript.attribs.src;
29
31
  var scriptBaseIndent = detectIndent(html, entryScript);
30
32
  var S0 = scriptBaseIndent;
31
33
  var S1 = scriptBaseIndent + space(2);
32
- var S2 = S1 + space(2);
33
34
  var script$ = module2DynamicImport({
34
35
  $: $,
35
36
  scriptTag: entryScript,
36
37
  changeScriptOrigin: changeScriptOrigin,
37
38
  ident: S1
38
39
  });
39
- script$ === null || script$ === void 0 || script$.html("".concat((_script$$html = script$.html()) === null || _script$$html === void 0 ? void 0 : _script$$html.trimEnd(), ".finally(() => {\n").concat(S2).concat(createImportFinallyResolve(appName, {
40
- indent: S2
41
- }).trim(), "\n").concat(S1, "});\n").concat(S0));
40
+ script$ === null || script$ === void 0 || script$.html("".concat((_script$$html = script$.html()) === null || _script$$html === void 0 ? void 0 : _script$$html.trimEnd(), ".then(() => {\n").concat(S1, " if (window.proxy) {\n").concat(S1, " const qiankunLifeCycle = window.proxy.qiankunLifeCycles;\n").concat(S1, " if (qiankunLifeCycle) {\n").concat(S1, " window.proxy.vpq_bootstrap((props) => qiankunLifeCycle.bootstrap && qiankunLifeCycle.bootstrap(props));\n").concat(S1, " window.proxy.vpq_mount((props) => qiankunLifeCycle.mount && qiankunLifeCycle.mount(props));\n").concat(S1, " window.proxy.vpq_unmount((props) => qiankunLifeCycle.unmount && qiankunLifeCycle.unmount(props));\n").concat(S1, " window.proxy.vpq_update((props) => qiankunLifeCycle.update && qiankunLifeCycle.update(props));\n").concat(S1, " window.dispatchEvent(new CustomEvent('qiankun:loaded'));\n").concat(S1, " }\n").concat(S1, " }\n").concat(S1, "}).catch((error) => {\n").concat(S1, " console.error(error);\n").concat(S1, " if (error.name === 'TypeError' && error.message && error.message.startsWith('Failed to fetch dynamically imported module:')) {\n").concat(S1, " window.dispatchEvent(new CustomEvent('qiankun:fetchEntryError', { detail: { url: '").concat(url, "', error } }));\n").concat(S1, " } else {\n").concat(S1, " window.dispatchEvent(new CustomEvent('qiankun:runtimeError', { detail: { error } }));\n").concat(S1, " }\n").concat(S1, "});\n").concat(S0));
41
+
42
+ // Transform modulepreload links
43
+ var preloadLinks = $('link[rel="modulepreload"]');
44
+ if (preloadLinks.length) {
45
+ var urls = preloadLinks.map(function (_, link) {
46
+ return $(link).attr('href');
47
+ }).get();
48
+ var P1 = detectIndent(html, preloadLinks.get(0));
49
+ preloadLinks.last().after("\n".concat(P1, "<script>\n").concat(P1, " const preloadUrls = [\n").concat(urls.map(function (url) {
50
+ return "".concat(P1, " ").concat(normalizeUrl(url, {
51
+ changeScriptOrigin: changeScriptOrigin
52
+ }));
53
+ }).join(',\n'), "\n").concat(P1, " ];\n").concat(P1, " preloadUrls.forEach((url) => {\n").concat(P1, " const link = document.createElement('link');\n").concat(P1, " link.rel = 'modulepreload';\n").concat(P1, " link.href = url;\n").concat(P1, " link.crossOrigin = 'anonymous';\n").concat(P1, " document.head.appendChild(link);\n").concat(P1, " });\n").concat(P1, "</script>"));
54
+ var texts = preloadLinks.map(function (_, link) {
55
+ var _link$next;
56
+ return ((_link$next = link.next) === null || _link$next === void 0 ? void 0 : _link$next.type) === 'text' ? link.next : null;
57
+ });
58
+ texts.remove();
59
+ preloadLinks.remove();
60
+ }
61
+
62
+ // Transform @react-refresh script
63
+ if (((_context$server = context.server) === null || _context$server === void 0 ? void 0 : _context$server.config.command) === 'serve') {
64
+ var scripts = $('head script[type=module]').toArray();
65
+ var refreshScript = scripts.find(function (s) {
66
+ var _$$html;
67
+ return /@react-refresh";$/m.test((_$$html = $(s).html()) !== null && _$$html !== void 0 ? _$$html : '');
68
+ });
69
+ if (refreshScript) {
70
+ var refreshScript$ = $(refreshScript);
71
+ var R1 = detectIndent(html, refreshScript) + space(2);
72
+ var content = refreshScript$.html();
73
+ var regExp = /import\s*{([^}]*)}\s*from\s*"([^"]*@react-refresh)";/m;
74
+ var match = content === null || content === void 0 ? void 0 : content.match(regExp);
75
+ if (content && match) {
76
+ var sentence = match[0];
77
+ var imports = match[1];
78
+ var from = match[2];
79
+ var rest = content.replace(sentence, '');
80
+ refreshScript$.removeAttr('type');
81
+ refreshScript$.html("\n".concat(R1, "import(").concat(normalizeUrl(from, {
82
+ changeScriptOrigin: changeScriptOrigin
83
+ }), ").then(({").concat(imports, "}) => {\n").concat(R1, " ").concat(rest.split('\n').map(function (s) {
84
+ return s.trim();
85
+ }).filter(Boolean).join("\n".concat(R1, " ")), "\n").concat(R1, "});"));
86
+ }
87
+ }
88
+ }
89
+
90
+ // Add extra script to export lifecycles
42
91
  var bodyBaseIndent = detectIndent(html, $('body').get(0));
43
92
  var B1 = bodyBaseIndent + space(2);
44
93
  var B2 = B1 + space(2);
45
- $('body').append("\n".concat(B1, "<script>\n").concat(B2).concat(createQiankunHelper(appName, {
46
- indent: B2 + space(2)
47
- }).trim(), "\n").concat(B1, "</script>\n"));
94
+ $('body').append("\n".concat(B1, "<script>\n").concat(B2).concat(exportLifeCycles(appName, {
95
+ indent: B2
96
+ }), "\n").concat(B1, "</script>\n"));
48
97
  var output = $.html();
49
98
  return output;
50
99
  } else {
@@ -55,28 +104,26 @@ var qiankunPlugin = function qiankunPlugin(appName) {
55
104
  configureServer: function configureServer(server) {
56
105
  var base = server.config.base;
57
106
  return function () {
58
- var patchFiles = ["".concat(base, "@vite/client")];
59
- patchFiles.forEach(function (file) {
60
- server.middlewares.use(file, function (req, res, next) {
61
- var end = res.end.bind(res);
62
- res.end = function (chunk) {
63
- if (typeof chunk === 'string') {
64
- var $ = load(chunk);
65
- module2DynamicImport({
66
- $: $,
67
- scriptTag: $("script[src=\"".concat(file, "\"]")).get(0),
68
- changeScriptOrigin: changeScriptOrigin
69
- });
70
- chunk = $.html();
71
- }
72
- for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
73
- rest[_key - 1] = arguments[_key];
74
- }
75
- end.apply(void 0, [chunk].concat(rest));
76
- return this;
77
- };
78
- next();
79
- });
107
+ // Only apply to / i.e. the mount point of the app
108
+ server.middlewares.use(function (req, res, next) {
109
+ var end = res.end.bind(res);
110
+ res.end = function (chunk) {
111
+ if (typeof chunk === 'string') {
112
+ var $ = load(chunk);
113
+ module2DynamicImport({
114
+ $: $,
115
+ scriptTag: $("script[src=\"".concat(base, "@vite/client\"]")).get(0),
116
+ changeScriptOrigin: changeScriptOrigin
117
+ });
118
+ chunk = $.html();
119
+ }
120
+ for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
121
+ rest[_key - 1] = arguments[_key];
122
+ }
123
+ end.apply(void 0, [chunk].concat(rest));
124
+ return this;
125
+ };
126
+ next();
80
127
  });
81
128
  };
82
129
  }
@@ -93,27 +140,19 @@ function module2DynamicImport(options) {
93
140
  }
94
141
  var script$ = $(scriptTag);
95
142
  var moduleSrc = script$.attr('src');
96
- var appendBase = "''";
97
- if (changeScriptOrigin) {
98
- appendBase = "window.proxy ? window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || '' : ''";
99
- }
100
143
  script$.removeAttr('src');
101
144
  script$.removeAttr('type');
102
145
  var space = ident;
103
- script$.html("\n".concat(space, "const publicUrl = ").concat(appendBase, ";\n").concat(space, "let assetUrl = '").concat(moduleSrc, "';\n").concat(space, "if (!assetUrl.match(/^https?/i)) {\n").concat(space, " assetUrl = publicUrl + assetUrl;\n").concat(space, "}\n").concat(space, "import(assetUrl)"));
146
+ script$.html("\n".concat(space, "import(").concat(normalizeUrl(moduleSrc, {
147
+ changeScriptOrigin: changeScriptOrigin
148
+ }), ")"));
104
149
  return script$;
105
150
  }
106
- function createImportFinallyResolve(qiankunName, options) {
151
+ function exportLifeCycles(qiankunName, options) {
107
152
  var _ref = options !== null && options !== void 0 ? options : {},
108
153
  _ref$indent = _ref.indent,
109
154
  space = _ref$indent === void 0 ? ' ' : _ref$indent;
110
- return "\n".concat(space, "const qiankunLifeCycle = window.moudleQiankunAppLifeCycles && window.moudleQiankunAppLifeCycles['").concat(qiankunName, "'];\n").concat(space, "if (qiankunLifeCycle) {\n").concat(space, " window.proxy.vitemount((props) => qiankunLifeCycle.mount(props));\n").concat(space, " window.proxy.viteunmount((props) => qiankunLifeCycle.unmount(props));\n").concat(space, " window.proxy.vitebootstrap(() => qiankunLifeCycle.bootstrap());\n").concat(space, " window.proxy.viteupdate((props) => qiankunLifeCycle.update(props));\n").concat(space, "}\n");
111
- }
112
- function createQiankunHelper(qiankunName, options) {
113
- var _ref2 = options !== null && options !== void 0 ? options : {},
114
- _ref2$indent = _ref2.indent,
115
- space = _ref2$indent === void 0 ? ' ' : _ref2$indent;
116
- return "\n".concat(space, "const createDeffer = (hookName) => {\n").concat(space, " const d = new Promise((resolve, reject) => {\n").concat(space, " window.proxy && (window.proxy[`vite${hookName}`] = resolve)\n").concat(space, " })\n").concat(space, " return props => d.then(fn => fn(props));\n").concat(space, "}\n").concat(space, "const bootstrap = createDeffer('bootstrap');\n").concat(space, "const mount = createDeffer('mount');\n").concat(space, "const unmount = createDeffer('unmount');\n").concat(space, "const update = createDeffer('update');\n\n").concat(space, ";(global => {\n").concat(space, " global.qiankunName = '").concat(qiankunName, "';\n").concat(space, " global['").concat(qiankunName, "'] = {\n").concat(space, " bootstrap,\n").concat(space, " mount,\n").concat(space, " unmount,\n").concat(space, " update\n").concat(space, " };\n").concat(space, "})(window);\n");
155
+ return "\n".concat(space, "const makeLifeCycle = (hookName) => {\n").concat(space, " const promise = new Promise((resolve, reject) => {\n").concat(space, " if (window.proxy) {\n").concat(space, " window.proxy[`vpq_${hookName}`] = resolve;\n").concat(space, " }\n").concat(space, " })\n").concat(space, " return (props) => promise.then(fn => fn(props));\n").concat(space, "};\n").concat(space, "window['").concat(qiankunName, "'] = {\n").concat(space, " bootstrap: makeLifeCycle('bootstrap'),\n").concat(space, " mount: makeLifeCycle('mount'),\n").concat(space, " unmount: makeLifeCycle('unmount'),\n").concat(space, " update: makeLifeCycle('update')\n").concat(space, "};").trimStart();
117
156
  }
118
157
  export default qiankunPlugin;
119
158
  //# sourceMappingURL=index.js.map
package/es/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["load","detectIndent","space","qiankunPlugin","appName","pluginOptions","arguments","length","undefined","_pluginOptions$change","changeScriptOrigin","name","transformIndexHtml","html","context","_$$get","$","sourceCodeLocationInfo","entryScript","get","_script$$html","scriptBaseIndent","S0","S1","S2","script$","module2DynamicImport","scriptTag","ident","concat","trimEnd","createImportFinallyResolve","indent","trim","bodyBaseIndent","B1","B2","append","createQiankunHelper","output","console","warn","configureServer","server","base","config","patchFiles","forEach","file","middlewares","use","req","res","next","end","bind","chunk","_len","rest","Array","_key","apply","options","_options$ident","moduleSrc","attr","appendBase","removeAttr","qiankunName","_ref","_ref$indent","_ref2","_ref2$indent"],"sources":["../src/index.ts"],"sourcesContent":["import type { CheerioAPI } from 'cheerio';\nimport { load } from 'cheerio';\nimport type { Element } from 'domhandler';\nimport type { PluginOption } from 'vite';\nimport { detectIndent, space } from './utils';\n\nexport * from './helper';\n\nexport interface MicroOption {\n /**\n * Whether to change the origin of entry script tag for micro frontend. It's useful when the micro\n * frontend is deployed on a different domain or path.\n *\n * > If the origin by the qiankun's default algorithm is not correct for you, please try the\n * > [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @default true\n */\n changeScriptOrigin?: boolean;\n}\ntype PluginFn = (appName: string, pluginOptions?: MicroOption) => PluginOption;\n\n/**\n * Vite plugin for integrating with Qiankun micro frontend.\n *\n * @param appName The name of the Qiankun sub app.\n * @param pluginOptions Options for configuring the micro frontend behavior.\n *\n * > If the micro app is deployed on a different domain or path, you may need to adjust the public\n * > path. Please have a look at the [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @returns A Vite plugin option object.\n */\nconst qiankunPlugin: PluginFn = (appName, pluginOptions = {}) => {\n const { changeScriptOrigin = true } = pluginOptions;\n\n return {\n name: 'vite-plugin-qiankun',\n\n transformIndexHtml(html: string, context) {\n const $ = load(html, { sourceCodeLocationInfo: true });\n const entryScript =\n $('script[entry]').get(0) ?? $('body script[type=module], head script[crossorigin=\"\"]').get(0);\n if (entryScript) {\n const scriptBaseIndent = detectIndent(html, entryScript);\n const S0 = scriptBaseIndent;\n const S1 = scriptBaseIndent + space(2);\n const S2 = S1 + space(2);\n const script$ = module2DynamicImport({\n $,\n scriptTag: entryScript,\n changeScriptOrigin,\n ident: S1,\n });\n script$?.html(`${script$.html()?.trimEnd()}.finally(() => {\n${S2}${createImportFinallyResolve(appName, { indent: S2 }).trim()}\n${S1}});\n${S0}`);\n\n const bodyBaseIndent = detectIndent(html, $('body').get(0));\n const B1 = bodyBaseIndent + space(2);\n const B2 = B1 + space(2);\n $('body').append(`\n${B1}<script>\n${B2}${createQiankunHelper(appName, { indent: B2 + space(2) }).trim()}\n${B1}</script>\n`);\n const output = $.html();\n return output;\n } else {\n console.warn('\\x1b[33m%s\\x1b[0m', '⚠️ Patch for qiankun failed, because the entry script was not found.');\n return html;\n }\n },\n configureServer(server) {\n const base = server.config.base;\n return () => {\n const patchFiles = [`${base}@vite/client`];\n patchFiles.forEach((file) => {\n server.middlewares.use(file, (req, res, next) => {\n const end = res.end.bind(res);\n res.end = function (this: typeof res, chunk: unknown, ...rest: any[]) {\n if (typeof chunk === 'string') {\n const $ = load(chunk);\n module2DynamicImport({ $, scriptTag: $(`script[src=\"${file}\"]`).get(0), changeScriptOrigin });\n chunk = $.html();\n }\n end(chunk, ...rest);\n return this;\n } as unknown as typeof res.end;\n next();\n });\n });\n };\n },\n };\n};\n\nfunction module2DynamicImport(\n options: { $: CheerioAPI; scriptTag: Element | undefined; ident?: string } & Pick<MicroOption, 'changeScriptOrigin'>,\n) {\n const { $, scriptTag, changeScriptOrigin, ident = '' } = options;\n if (!scriptTag) {\n return;\n }\n const script$ = $(scriptTag);\n const moduleSrc = script$.attr('src');\n let appendBase = \"''\";\n if (changeScriptOrigin) {\n appendBase = \"window.proxy ? window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || '' : ''\";\n }\n script$.removeAttr('src');\n script$.removeAttr('type');\n const space = ident;\n script$.html(`\n${space}const publicUrl = ${appendBase};\n${space}let assetUrl = '${moduleSrc}';\n${space}if (!assetUrl.match(/^https?/i)) {\n${space} assetUrl = publicUrl + assetUrl;\n${space}}\n${space}import(assetUrl)`);\n return script$;\n}\n\nfunction createImportFinallyResolve(qiankunName: string, options?: { indent?: string }) {\n const { indent: space = ' ' } = options ?? {};\n return `\n${space}const qiankunLifeCycle = window.moudleQiankunAppLifeCycles && window.moudleQiankunAppLifeCycles['${qiankunName}'];\n${space}if (qiankunLifeCycle) {\n${space} window.proxy.vitemount((props) => qiankunLifeCycle.mount(props));\n${space} window.proxy.viteunmount((props) => qiankunLifeCycle.unmount(props));\n${space} window.proxy.vitebootstrap(() => qiankunLifeCycle.bootstrap());\n${space} window.proxy.viteupdate((props) => qiankunLifeCycle.update(props));\n${space}}\n`;\n}\n\nfunction createQiankunHelper(qiankunName: string, options?: { indent?: string }) {\n const { indent: space = ' ' } = options ?? {};\n return `\n${space}const createDeffer = (hookName) => {\n${space} const d = new Promise((resolve, reject) => {\n${space} window.proxy && (window.proxy[\\`vite\\${hookName}\\`] = resolve)\n${space} })\n${space} return props => d.then(fn => fn(props));\n${space}}\n${space}const bootstrap = createDeffer('bootstrap');\n${space}const mount = createDeffer('mount');\n${space}const unmount = createDeffer('unmount');\n${space}const update = createDeffer('update');\n\n${space};(global => {\n${space} global.qiankunName = '${qiankunName}';\n${space} global['${qiankunName}'] = {\n${space} bootstrap,\n${space} mount,\n${space} unmount,\n${space} update\n${space} };\n${space}})(window);\n`;\n}\n\nexport default qiankunPlugin;\n"],"mappings":"AACA,SAASA,IAAI,QAAQ,SAAS;AAG9B,SAASC,YAAY,EAAEC,KAAK;AAE5B;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,aAAuB,GAAG,SAA1BA,aAAuBA,CAAIC,OAAO,EAAyB;EAAA,IAAvBC,aAAa,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAC1D,IAAAG,qBAAA,GAAsCJ,aAAa,CAA3CK,kBAAkB;IAAlBA,kBAAkB,GAAAD,qBAAA,cAAG,IAAI,GAAAA,qBAAA;EAEjC,OA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AAK,uEAAA2B,MAAA,CACL3B,KAAK,YAAA2B,MAAA,CACL3B,KAAK,kDAAA2B,MAAA,CACL3B,KAAK,SAAA2B,MAAA,CACL3B,KAAK,oDAAA2B,MAAA,CACL3B,KAAK,4CAAA2B,MAAA,CACL3B,KAAK,gDAAA2B,MAAA,CACL3B,KAAK,gDAAA2B,MAAA,CAEL3B,KAAK,qBAAA2B,MAAA,CACL3B,KAAK,8BAAA2B,MAAA,CAA2BuC,WAAW,UAAAvC,MAAA,CAC3C3B,KAAK,gBAAA2B,MAAA,CAAauC,WAAW,cAAAvC,MAAA,CAC7B3B,KAAK,sBAAA2B,MAAA,CACL3B,KAAK,kBAAA2B,MAAA,CACL3B,KAAK,oBAAA2B,MAAA,CACL3B,KAAK,kBAAA2B,MAAA,CACL3B,KAAK,YAAA2B,MAAA,CACL3B,KAAK;AAEP;AAEA,eAAeC,aAAa"}
1
+ {"version":3,"names":["load","detectIndent","normalizeUrl","space","qiankunPlugin","appName","pluginOptions","arguments","length","undefined","_pluginOptions$change","changeScriptOrigin","name","transformIndexHtml","html","context","_$$get","$","sourceCodeLocationInfo","entryScript","get","_script$$html","_context$server","url","attribs","src","scriptBaseIndent","S0","S1","script$","module2DynamicImport","scriptTag","ident","concat","trimEnd","preloadLinks","urls","map","_","link","attr","P1","last","after","join","texts","_link$next","next","type","remove","server","config","command","scripts","toArray","refreshScript","find","s","_$$html","test","refreshScript$","R1","content","regExp","match","sentence","imports","from","rest","replace","removeAttr","split","trim","filter","Boolean","bodyBaseIndent","B1","B2","append","exportLifeCycles","indent","output","console","warn","configureServer","base","middlewares","use","req","res","end","bind","chunk","_len","Array","_key","apply","options","_options$ident","moduleSrc","qiankunName","_ref","_ref$indent","trimStart"],"sources":["../src/index.ts"],"sourcesContent":["import type { CheerioAPI } from 'cheerio';\nimport { load } from 'cheerio';\nimport type { Element } from 'domhandler';\nimport type { PluginOption } from 'vite';\nimport { detectIndent, normalizeUrl, space } from './utils';\n\nexport * from './helper';\n\nexport interface MicroOption {\n /**\n * Whether to change the origin of entry script tag for micro frontend. It's useful when the micro\n * frontend is deployed on a different domain or path.\n *\n * > If the origin by the qiankun's default algorithm is not correct for you, please try the\n * > [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @default true\n */\n changeScriptOrigin?: boolean;\n}\ntype PluginFn = (appName: string, pluginOptions?: MicroOption) => PluginOption;\n\n/**\n * Vite plugin for integrating with Qiankun micro frontend.\n *\n * @param appName The name of the Qiankun sub app.\n * @param pluginOptions Options for configuring the micro frontend behavior.\n *\n * > If the micro app is deployed on a different domain or path, you may need to adjust the public\n * > path. Please have a look at the [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @returns A Vite plugin option object.\n */\nconst qiankunPlugin: PluginFn = (appName, pluginOptions = {}) => {\n const { changeScriptOrigin = true } = pluginOptions;\n\n return {\n name: 'vite-plugin-qiankun',\n\n transformIndexHtml(html: string, context) {\n const $ = load(html, { sourceCodeLocationInfo: true });\n // Transform entry script\n const entryScript =\n $('script[entry]').get(0) ?? $('body script[type=module], head script[crossorigin=\"\"]').get(0);\n if (entryScript) {\n const url = entryScript.attribs.src;\n const scriptBaseIndent = detectIndent(html, entryScript);\n const S0 = scriptBaseIndent;\n const S1 = scriptBaseIndent + space(2);\n const script$ = module2DynamicImport({\n $,\n scriptTag: entryScript,\n changeScriptOrigin,\n ident: S1,\n });\n script$?.html(\n `${script$.html()?.trimEnd()}.then(() => {\n${S1} if (window.proxy) {\n${S1} const qiankunLifeCycle = window.proxy.qiankunLifeCycles;\n${S1} if (qiankunLifeCycle) {\n${S1} window.proxy.vpq_bootstrap((props) => qiankunLifeCycle.bootstrap && qiankunLifeCycle.bootstrap(props));\n${S1} window.proxy.vpq_mount((props) => qiankunLifeCycle.mount && qiankunLifeCycle.mount(props));\n${S1} window.proxy.vpq_unmount((props) => qiankunLifeCycle.unmount && qiankunLifeCycle.unmount(props));\n${S1} window.proxy.vpq_update((props) => qiankunLifeCycle.update && qiankunLifeCycle.update(props));\n${S1} window.dispatchEvent(new CustomEvent('qiankun:loaded'));\n${S1} }\n${S1} }\n${S1}}).catch((error) => {\n${S1} console.error(error);\n${S1} if (error.name === 'TypeError' && error.message && error.message.startsWith('Failed to fetch dynamically imported module:')) {\n${S1} window.dispatchEvent(new CustomEvent('qiankun:fetchEntryError', { detail: { url: '${url}', error } }));\n${S1} } else {\n${S1} window.dispatchEvent(new CustomEvent('qiankun:runtimeError', { detail: { error } }));\n${S1} }\n${S1}});\n${S0}`,\n );\n\n // Transform modulepreload links\n const preloadLinks = $('link[rel=\"modulepreload\"]');\n if (preloadLinks.length) {\n const urls = preloadLinks.map((_, link) => $(link).attr('href')).get();\n const P1 = detectIndent(html, preloadLinks.get(0));\n preloadLinks.last().after(`\n${P1}<script>\n${P1} const preloadUrls = [\n${urls.map((url) => `${P1} ${normalizeUrl(url, { changeScriptOrigin })}`).join(',\\n')}\n${P1} ];\n${P1} preloadUrls.forEach((url) => {\n${P1} const link = document.createElement('link');\n${P1} link.rel = 'modulepreload';\n${P1} link.href = url;\n${P1} link.crossOrigin = 'anonymous';\n${P1} document.head.appendChild(link);\n${P1} });\n${P1}</script>`);\n const texts = preloadLinks.map((_, link) => (link.next?.type === 'text' ? link.next : null));\n texts.remove();\n preloadLinks.remove();\n }\n\n // Transform @react-refresh script\n if (context.server?.config.command === 'serve') {\n const scripts = $('head script[type=module]').toArray();\n const refreshScript = scripts.find((s) => /@react-refresh\";$/m.test($(s).html() ?? ''));\n if (refreshScript) {\n const refreshScript$ = $(refreshScript);\n const R1 = detectIndent(html, refreshScript) + space(2);\n const content = refreshScript$.html();\n const regExp = /import\\s*{([^}]*)}\\s*from\\s*\"([^\"]*@react-refresh)\";/m;\n const match = content?.match(regExp);\n if (content && match) {\n const sentence = match[0];\n const imports = match[1];\n const from = match[2];\n const rest = content.replace(sentence, '');\n refreshScript$.removeAttr('type');\n refreshScript$.html(`\n${R1}import(${normalizeUrl(from, { changeScriptOrigin })}).then(({${imports}}) => {\n${R1} ${rest\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean)\n .join(`\\n${R1} `)}\n${R1}});`);\n }\n }\n }\n\n // Add extra script to export lifecycles\n const bodyBaseIndent = detectIndent(html, $('body').get(0));\n const B1 = bodyBaseIndent + space(2);\n const B2 = B1 + space(2);\n $('body').append(`\n${B1}<script>\n${B2}${exportLifeCycles(appName, { indent: B2 })}\n${B1}</script>\n`);\n const output = $.html();\n return output;\n } else {\n console.warn('\\x1b[33m%s\\x1b[0m', '⚠️ Patch for qiankun failed, because the entry script was not found.');\n return html;\n }\n },\n configureServer(server) {\n const base = server.config.base;\n return () => {\n // Only apply to / i.e. the mount point of the app\n server.middlewares.use((req, res, next) => {\n const end = res.end.bind(res);\n res.end = function (this: typeof res, chunk: unknown, ...rest: any[]) {\n if (typeof chunk === 'string') {\n const $ = load(chunk);\n module2DynamicImport({ $, scriptTag: $(`script[src=\"${base}@vite/client\"]`).get(0), changeScriptOrigin });\n chunk = $.html();\n }\n end(chunk, ...rest);\n return this;\n } as unknown as typeof res.end;\n next();\n });\n };\n },\n };\n};\n\nfunction module2DynamicImport(\n options: { $: CheerioAPI; scriptTag: Element | undefined; ident?: string } & Pick<MicroOption, 'changeScriptOrigin'>,\n) {\n const { $, scriptTag, changeScriptOrigin, ident = '' } = options;\n if (!scriptTag) {\n return;\n }\n const script$ = $(scriptTag);\n const moduleSrc = script$.attr('src');\n script$.removeAttr('src');\n script$.removeAttr('type');\n const space = ident;\n script$.html(`\n${space}import(${normalizeUrl(moduleSrc, { changeScriptOrigin })})`);\n return script$;\n}\n\nfunction exportLifeCycles(qiankunName: string, options?: { indent?: string }) {\n const { indent: space = ' ' } = options ?? {};\n return `\n${space}const makeLifeCycle = (hookName) => {\n${space} const promise = new Promise((resolve, reject) => {\n${space} if (window.proxy) {\n${space} window.proxy[\\`vpq_\\${hookName}\\`] = resolve;\n${space} }\n${space} })\n${space} return (props) => promise.then(fn => fn(props));\n${space}};\n${space}window['${qiankunName}'] = {\n${space} bootstrap: makeLifeCycle('bootstrap'),\n${space} mount: makeLifeCycle('mount'),\n${space} unmount: makeLifeCycle('unmount'),\n${space} update: makeLifeCycle('update')\n${space}};`.trimStart();\n}\n\nexport default qiankunPlugin;\n"],"mappings":"AACA,SAASA,IAAI,QAAQ,SAAS;AAG9B,SAASC,YAAY,EAAEC,YAAY,EAAEC,KAAK;AAE1C;AAgBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,aAAuB,GAAG,SAA1BA,aAAuBA,CAAIC,OAAO,EAAyB;EAAA,IAAvBC,aAAa,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAG,CAAC,CAAC;EAC1D,IAAAG,qBAAA,GAAsCJ,aAAa,CAA3CK,kBAAkB;IAAlBA,kBAAkB,GAAAD,qBAAA,cAAG,IAAI,GAAAA,qBAAA;EAEjC,OAAO;IACLE,IAAI,EAAE,qBAAqB;IAE3BC,kBAAkB,WAAAA,mBAACC,IAAY,EAAEC,OAAO,EAAE;MAAA,IAAAC,MAAA;MACxC,IAAMC,CAAC,GAAGjB,IAAI,CAACc,IAAI,EAAE;QAAEI,sBAAsB,EAAE;MAAK,CAAC,CAAC;MACtD;MACA,IAAMC,WAAW,IAAAH,MAAA,GACfC,CAAC,CAAC,eAAe,CAAC,CAACG,GAAG,CAAC,CAAC,CAAC,cAAAJ,MAAA,cAAAA,MAAA,GAAIC,CAAC,CAAC,uDAAuD,CAAC,CAACG,GAAG,CAAC,CAAC,CAAC;MAChG,IAAID,WAAW,EAAE;QAAA,IAAAE,aAAA,EAAAC,eAAA;QACf,IAAMC,GAAG,GAAGJ,WAAW,CAACK,OAAO,CAACC,GAAG;QACnC,IAAMC,gBAAgB,GAAGzB,YAAY,CAACa,IAAI,EAAEK,WAAW,CAAC;QACxD,IAAMQ,EAAE,GAAGD,gBAAgB;QAC3B,IAAME,EAAE,GAAGF,gBAAgB,GAAGvB,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,CAAC;EAC1B,IAAMnE,KAAK,GAAG6B,KAAK;EACnBH,OAAO,CAACf,IAAI,MAAAmB,MAAA,CACZ9B,KAAK,aAAA8B,MAAA,CAAU/B,YAAY,CAACiG,SAAS,EAAE;IAAExF,kBAAkB,EAAlBA;EAAmB,CAAC,CAAC,MAAG,CAAC;EAClE,OAAOkB,OAAO;AAChB;AAEA,SAASkD,gBAAgBA,CAACqB,WAAmB,EAAEH,OAA6B,EAAE;EAC5E,IAAAI,IAAA,GAAqCJ,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAI,CAAC,CAAC;IAAAK,WAAA,GAAAD,IAAA,CAA1CrB,MAAM;IAAE7E,KAAK,GAAAmG,WAAA,cAAG,QAAQ,GAAAA,WAAA;EAChC,OAAO,KAAArE,MAAA,CACP9B,KAAK,6CAAA8B,MAAA,CACL9B,KAAK,4DAAA8B,MAAA,CACL9B,KAAK,+BAAA8B,MAAA,CACL9B,KAAK,wDAAA8B,MAAA,CACL9B,KAAK,aAAA8B,MAAA,CACL9B,KAAK,YAAA8B,MAAA,CACL9B,KAAK,0DAAA8B,MAAA,CACL9B,KAAK,UAAA8B,MAAA,CACL9B,KAAK,cAAA8B,MAAA,CAAWmE,WAAW,cAAAnE,MAAA,CAC3B9B,KAAK,gDAAA8B,MAAA,CACL9B,KAAK,wCAAA8B,MAAA,CACL9B,KAAK,4CAAA8B,MAAA,CACL9B,KAAK,yCAAA8B,MAAA,CACL9B,KAAK,QAAKoG,SAAS,CAAC,CAAC;AACvB;AAEA,eAAenG,aAAa"}
package/es/utils.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  import type { Element } from 'domhandler';
2
- export declare function detectIndent(html: string, entryScript: Element | undefined): string;
2
+ export declare function detectIndent(html: string, element: Element | undefined): string;
3
3
  export declare function space(num: number): string;
4
+ export declare function normalizeUrl(url: string | undefined, options?: {
5
+ changeScriptOrigin?: boolean;
6
+ }): string;
package/es/utils.js CHANGED
@@ -1,14 +1,14 @@
1
- export function detectIndent(html, entryScript) {
1
+ export function detectIndent(html, element) {
2
2
  var baseIndent = '';
3
- if (entryScript !== null && entryScript !== void 0 && entryScript.sourceCodeLocation) {
3
+ if (element !== null && element !== void 0 && element.sourceCodeLocation) {
4
4
  var newline = html.includes('\r\n') ? '\r\n' : '\n';
5
5
  var lines = html.split(newline);
6
- var lineStr = lines[entryScript.sourceCodeLocation.startLine - 1];
6
+ var lineStr = lines[element.sourceCodeLocation.startLine - 1];
7
7
  if (lineStr) {
8
- var startTag = '<script';
9
- var tagNameFromHtml = lineStr.substring(entryScript.sourceCodeLocation.startCol - 1, entryScript.sourceCodeLocation.startCol - 1 + startTag.length);
8
+ var startTag = "<".concat(element.tagName);
9
+ var tagNameFromHtml = lineStr.substring(element.sourceCodeLocation.startCol - 1, element.sourceCodeLocation.startCol - 1 + startTag.length);
10
10
  if (tagNameFromHtml === startTag) {
11
- for (var i = 0; i < entryScript.sourceCodeLocation.startCol - 1; i++) {
11
+ for (var i = 0; i < element.sourceCodeLocation.startCol - 1; i++) {
12
12
  if (/\s/.test(lineStr[i])) {
13
13
  baseIndent += lineStr[i];
14
14
  } else {
@@ -23,4 +23,14 @@ export function detectIndent(html, entryScript) {
23
23
  export function space(num) {
24
24
  return new Array(num + 1).join(' ');
25
25
  }
26
+ export function normalizeUrl(url, options) {
27
+ var _ref = options !== null && options !== void 0 ? options : {},
28
+ _ref$changeScriptOrig = _ref.changeScriptOrigin,
29
+ changeScriptOrigin = _ref$changeScriptOrig === void 0 ? true : _ref$changeScriptOrig;
30
+ var appendBase = "''";
31
+ if (changeScriptOrigin) {
32
+ appendBase = "window.proxy && window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || ''";
33
+ }
34
+ return url !== null && url !== void 0 && url.match(/^https?/i) ? "'".concat(url, "'") : "(".concat(appendBase, ") + '").concat(url, "'");
35
+ }
26
36
  //# sourceMappingURL=utils.js.map
package/es/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"names":["detectIndent","html","entryScript","baseIndent","sourceCodeLocation","newline","includes","lines","split","lineStr","startLine","startTag","tagNameFromHtml","substring","startCol","length","i","test","space","num","Array","join"],"sources":["../src/utils.ts"],"sourcesContent":["import type { Element } from 'domhandler';\n\nexport function detectIndent(html: string, entryScript: Element | undefined) {\n let baseIndent = '';\n if (entryScript?.sourceCodeLocation) {\n const newline = html.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lines = html.split(newline);\n const lineStr = lines[entryScript.sourceCodeLocation.startLine - 1];\n if (lineStr) {\n const startTag = '<script';\n const tagNameFromHtml = lineStr.substring(\n entryScript.sourceCodeLocation.startCol - 1,\n entryScript.sourceCodeLocation.startCol - 1 + startTag.length,\n );\n if (tagNameFromHtml === startTag) {\n for (let i = 0; i < entryScript.sourceCodeLocation.startCol - 1; i++) {\n if (/\\s/.test(lineStr[i])) {\n baseIndent += lineStr[i];\n } else {\n break;\n }\n }\n }\n }\n }\n return baseIndent;\n}\n\nexport function space(num: number) {\n return new Array(num + 1).join(' ');\n}\n"],"mappings":"AAEA,OAAO,SAASA,YAAYA,CAACC,IAAY,EAAEC,WAAgC,EAAE;EAC3E,IAAIC,UAAU,GAAG,EAAE;EACnB,IAAID,WAAW,aAAXA,WAAW,eAAXA,WAAW,CAAEE,kBAAkB,EAAE;IACnC,IAAMC,OAAO,GAAGJ,IAAI,CAACK,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI;IACrD,IAAMC,KAAK,GAAGN,IAAI,CAACO,KAAK,CAACH,OAAO,CAAC;IACjC,IAAMI,OAAO,GAAGF,KAAK,CAACL,WAAW,CAACE,kBAAkB,CAACM,SAAS,GAAG,CAAC,CAAC;IACnE,IAAID,OAAO,EAAE;MACX,IAAME,QAAQ,GAAG,SAAS;MAC1B,IAAMC,eAAe,GAAGH,OAAO,CAACI,SAAS,CACvCX,WAAW,CAACE,kBAAkB,CAACU,QAAQ,GAAG,CAAC,EAC3CZ,WAAW,CAACE,kBAAkB,CAACU,QAAQ,GAAG,CAAC,GAAGH,QAAQ,CAACI,MACzD,CAAC;MACD,IAAIH,eAAe,KAAKD,QAAQ,EAAE;QAChC,KAAK,IAAIK,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGd,WAAW,CAACE,kBAAkB,CAACU,QAAQ,GAAG,CAAC,EAAEE,CAAC,EAAE,EAAE;UACpE,IAAI,IAAI,CAACC,IAAI,CAACR,OAAO,CAACO,CAAC,CAAC,CAAC,EAAE;YACzBb,UAAU,IAAIM,OAAO,CAACO,CAAC,CAAC;UAC1B,CAAC,MAAM;YACL;UACF;QACF;MACF;IACF;EACF;EACA,OAAOb,UAAU;AACnB;AAEA,OAAO,SAASe,KAAKA,CAACC,GAAW,EAAE;EACjC,OAAO,IAAIC,KAAK,CAACD,GAAG,GAAG,CAAC,CAAC,CAACE,IAAI,CAAC,GAAG,CAAC;AACrC"}
1
+ {"version":3,"names":["detectIndent","html","element","baseIndent","sourceCodeLocation","newline","includes","lines","split","lineStr","startLine","startTag","concat","tagName","tagNameFromHtml","substring","startCol","length","i","test","space","num","Array","join","normalizeUrl","url","options","_ref","_ref$changeScriptOrig","changeScriptOrigin","appendBase","match"],"sources":["../src/utils.ts"],"sourcesContent":["import type { Element } from 'domhandler';\n\nexport function detectIndent(html: string, element: Element | undefined) {\n let baseIndent = '';\n if (element?.sourceCodeLocation) {\n const newline = html.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lines = html.split(newline);\n const lineStr = lines[element.sourceCodeLocation.startLine - 1];\n if (lineStr) {\n const startTag = `<${element.tagName}`;\n const tagNameFromHtml = lineStr.substring(\n element.sourceCodeLocation.startCol - 1,\n element.sourceCodeLocation.startCol - 1 + startTag.length,\n );\n if (tagNameFromHtml === startTag) {\n for (let i = 0; i < element.sourceCodeLocation.startCol - 1; i++) {\n if (/\\s/.test(lineStr[i])) {\n baseIndent += lineStr[i];\n } else {\n break;\n }\n }\n }\n }\n }\n return baseIndent;\n}\n\nexport function space(num: number) {\n return new Array(num + 1).join(' ');\n}\n\nexport function normalizeUrl(url: string | undefined, options?: { changeScriptOrigin?: boolean }) {\n const { changeScriptOrigin = true } = options ?? {};\n let appendBase = \"''\";\n if (changeScriptOrigin) {\n appendBase = \"window.proxy && window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || ''\";\n }\n return url?.match(/^https?/i) ? `'${url}'` : `(${appendBase}) + '${url}'`;\n}\n"],"mappings":"AAEA,OAAO,SAASA,YAAYA,CAACC,IAAY,EAAEC,OAA4B,EAAE;EACvE,IAAIC,UAAU,GAAG,EAAE;EACnB,IAAID,OAAO,aAAPA,OAAO,eAAPA,OAAO,CAAEE,kBAAkB,EAAE;IAC/B,IAAMC,OAAO,GAAGJ,IAAI,CAACK,QAAQ,CAAC,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI;IACrD,IAAMC,KAAK,GAAGN,IAAI,CAACO,KAAK,CAACH,OAAO,CAAC;IACjC,IAAMI,OAAO,GAAGF,KAAK,CAACL,OAAO,CAACE,kBAAkB,CAACM,SAAS,GAAG,CAAC,CAAC;IAC/D,IAAID,OAAO,EAAE;MACX,IAAME,QAAQ,OAAAC,MAAA,CAAOV,OAAO,CAACW,OAAO,CAAE;MACtC,IAAMC,eAAe,GAAGL,OAAO,CAACM,SAAS,CACvCb,OAAO,CAACE,kBAAkB,CAACY,QAAQ,GAAG,CAAC,EACvCd,OAAO,CAACE,kBAAkB,CAACY,QAAQ,GAAG,CAAC,GAAGL,QAAQ,CAACM,MACrD,CAAC;MACD,IAAIH,eAAe,KAAKH,QAAQ,EAAE;QAChC,KAAK,IAAIO,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGhB,OAAO,CAACE,kBAAkB,CAACY,QAAQ,GAAG,CAAC,EAAEE,CAAC,EAAE,EAAE;UAChE,IAAI,IAAI,CAACC,IAAI,CAACV,OAAO,CAACS,CAAC,CAAC,CAAC,EAAE;YACzBf,UAAU,IAAIM,OAAO,CAACS,CAAC,CAAC;UAC1B,CAAC,MAAM;YACL;UACF;QACF;MACF;IACF;EACF;EACA,OAAOf,UAAU;AACnB;AAEA,OAAO,SAASiB,KAAKA,CAACC,GAAW,EAAE;EACjC,OAAO,IAAIC,KAAK,CAACD,GAAG,GAAG,CAAC,CAAC,CAACE,IAAI,CAAC,GAAG,CAAC;AACrC;AAEA,OAAO,SAASC,YAAYA,CAACC,GAAuB,EAAEC,OAA0C,EAAE;EAChG,IAAAC,IAAA,GAAsCD,OAAO,aAAPA,OAAO,cAAPA,OAAO,GAAI,CAAC,CAAC;IAAAE,qBAAA,GAAAD,IAAA,CAA3CE,kBAAkB;IAAlBA,kBAAkB,GAAAD,qBAAA,cAAG,IAAI,GAAAA,qBAAA;EACjC,IAAIE,UAAU,GAAG,IAAI;EACrB,IAAID,kBAAkB,EAAE;IACtBC,UAAU,GAAG,wEAAwE;EACvF;EACA,OAAOL,GAAG,aAAHA,GAAG,eAAHA,GAAG,CAAEM,KAAK,CAAC,UAAU,CAAC,OAAAnB,MAAA,CAAOa,GAAG,aAAAb,MAAA,CAAUkB,UAAU,WAAAlB,MAAA,CAAQa,GAAG,MAAG;AAC3E"}
package/lib/helper.d.ts CHANGED
@@ -3,15 +3,16 @@ export interface QiankunProps {
3
3
  [x: string]: unknown;
4
4
  }
5
5
  export interface QiankunLifeCycle {
6
- bootstrap: (props?: QiankunProps) => void | Promise<void>;
7
- mount: (props: QiankunProps) => void | Promise<void>;
8
- unmount: (props: QiankunProps) => void | Promise<void>;
9
- update: (props: QiankunProps) => void | Promise<void>;
6
+ bootstrap?: (props?: QiankunProps) => void | Promise<void>;
7
+ mount?: (props: QiankunProps) => void | Promise<void>;
8
+ unmount?: (props: QiankunProps) => void | Promise<void>;
9
+ update?: (props: QiankunProps) => void | Promise<void>;
10
10
  }
11
11
  export interface QiankunWindow {
12
12
  __POWERED_BY_QIANKUN__?: boolean;
13
+ __INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
14
+ qiankunLifeCycles?: QiankunLifeCycle;
13
15
  [x: string]: any;
14
16
  }
15
17
  export declare const qiankunWindow: QiankunWindow;
16
- export declare const renderWithQiankun: (qiankunLifeCycle: QiankunLifeCycle) => void;
17
- export default renderWithQiankun;
18
+ export declare const exportQiankunLifeCycles: (qiankunLifeCycle: QiankunLifeCycle) => void;
package/lib/helper.js CHANGED
@@ -19,26 +19,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  // src/helper.ts
20
20
  var helper_exports = {};
21
21
  __export(helper_exports, {
22
- default: () => helper_default,
23
- qiankunWindow: () => qiankunWindow,
24
- renderWithQiankun: () => renderWithQiankun
22
+ exportQiankunLifeCycles: () => exportQiankunLifeCycles,
23
+ qiankunWindow: () => qiankunWindow
25
24
  });
26
25
  module.exports = __toCommonJS(helper_exports);
27
26
  var qiankunWindow = typeof window !== "undefined" ? window.proxy || window : {};
28
- var renderWithQiankun = (qiankunLifeCycle) => {
27
+ var exportQiankunLifeCycles = (qiankunLifeCycle) => {
29
28
  if (qiankunWindow == null ? void 0 : qiankunWindow.__POWERED_BY_QIANKUN__) {
30
- if (!window.moudleQiankunAppLifeCycles) {
31
- window.moudleQiankunAppLifeCycles = {};
32
- }
33
- if (qiankunWindow.qiankunName) {
34
- window.moudleQiankunAppLifeCycles[qiankunWindow.qiankunName] = qiankunLifeCycle;
35
- }
29
+ qiankunWindow.qiankunLifeCycles = qiankunLifeCycle;
36
30
  }
37
31
  };
38
- var helper_default = renderWithQiankun;
39
32
  // Annotate the CommonJS export names for ESM import in node:
40
33
  0 && (module.exports = {
41
- qiankunWindow,
42
- renderWithQiankun
34
+ exportQiankunLifeCycles,
35
+ qiankunWindow
43
36
  });
44
37
  //# sourceMappingURL=helper.js.map
package/lib/helper.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/helper.ts"],
4
- "sourcesContent": ["export interface QiankunProps {\n container?: HTMLElement;\n [x: string]: unknown;\n}\n\nexport interface QiankunLifeCycle {\n bootstrap: (props?: QiankunProps) => void | Promise<void>;\n mount: (props: QiankunProps) => void | Promise<void>;\n unmount: (props: QiankunProps) => void | Promise<void>;\n update: (props: QiankunProps) => void | Promise<void>;\n}\n\nexport interface QiankunWindow {\n __POWERED_BY_QIANKUN__?: boolean;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any;\n}\n\nexport const qiankunWindow: QiankunWindow = typeof window !== 'undefined' ? window.proxy || window : {};\n\nexport const renderWithQiankun = (qiankunLifeCycle: QiankunLifeCycle) => {\n // 函数只有一次执行机会,需要把生命周期赋值给全局\n if (qiankunWindow?.__POWERED_BY_QIANKUN__) {\n if (!window.moudleQiankunAppLifeCycles) {\n window.moudleQiankunAppLifeCycles = {};\n }\n if (qiankunWindow.qiankunName) {\n window.moudleQiankunAppLifeCycles[qiankunWindow.qiankunName] = qiankunLifeCycle;\n }\n }\n};\n\nexport default renderWithQiankun;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBO,IAAM,gBAA+B,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS,CAAC;AAE/F,IAAM,oBAAoB,CAAC,qBAAuC;AAEvE,MAAI,+CAAe,wBAAwB;AACzC,QAAI,CAAC,OAAO,4BAA4B;AACtC,aAAO,6BAA6B,CAAC;AAAA,IACvC;AACA,QAAI,cAAc,aAAa;AAC7B,aAAO,2BAA2B,cAAc,WAAW,IAAI;AAAA,IACjE;AAAA,EACF;AACF;AAEA,IAAO,iBAAQ;",
4
+ "sourcesContent": ["export interface QiankunProps {\n container?: HTMLElement;\n [x: string]: unknown;\n}\n\nexport interface QiankunLifeCycle {\n bootstrap?: (props?: QiankunProps) => void | Promise<void>;\n mount?: (props: QiankunProps) => void | Promise<void>;\n unmount?: (props: QiankunProps) => void | Promise<void>;\n update?: (props: QiankunProps) => void | Promise<void>;\n}\n\nexport interface QiankunWindow {\n __POWERED_BY_QIANKUN__?: boolean;\n __INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;\n qiankunLifeCycles?: QiankunLifeCycle;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: string]: any;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const qiankunWindow: QiankunWindow = typeof window !== 'undefined' ? (window as any).proxy || window : {};\n\nexport const exportQiankunLifeCycles = (qiankunLifeCycle: QiankunLifeCycle) => {\n // The function has only one chance to execute, and the lifecycle needs to be assigned to the global scope.\n if (qiankunWindow?.__POWERED_BY_QIANKUN__) {\n qiankunWindow.qiankunLifeCycles = qiankunLifeCycle;\n }\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBO,IAAM,gBAA+B,OAAO,WAAW,cAAe,OAAe,SAAS,SAAS,CAAC;AAExG,IAAM,0BAA0B,CAAC,qBAAuC;AAE7E,MAAI,+CAAe,wBAAwB;AACzC,kBAAc,oBAAoB;AAAA,EACpC;AACF;",
6
6
  "names": []
7
7
  }
package/lib/index.js CHANGED
@@ -31,30 +31,95 @@ var qiankunPlugin = (appName, pluginOptions = {}) => {
31
31
  return {
32
32
  name: "vite-plugin-qiankun",
33
33
  transformIndexHtml(html, context) {
34
- var _a;
34
+ var _a, _b;
35
35
  const $ = (0, import_cheerio.load)(html, { sourceCodeLocationInfo: true });
36
36
  const entryScript = $("script[entry]").get(0) ?? $('body script[type=module], head script[crossorigin=""]').get(0);
37
37
  if (entryScript) {
38
+ const url = entryScript.attribs.src;
38
39
  const scriptBaseIndent = (0, import_utils.detectIndent)(html, entryScript);
39
40
  const S0 = scriptBaseIndent;
40
41
  const S1 = scriptBaseIndent + (0, import_utils.space)(2);
41
- const S2 = S1 + (0, import_utils.space)(2);
42
42
  const script$ = module2DynamicImport({
43
43
  $,
44
44
  scriptTag: entryScript,
45
45
  changeScriptOrigin,
46
46
  ident: S1
47
47
  });
48
- script$ == null ? void 0 : script$.html(`${(_a = script$.html()) == null ? void 0 : _a.trimEnd()}.finally(() => {
49
- ${S2}${createImportFinallyResolve(appName, { indent: S2 }).trim()}
48
+ script$ == null ? void 0 : script$.html(
49
+ `${(_a = script$.html()) == null ? void 0 : _a.trimEnd()}.then(() => {
50
+ ${S1} if (window.proxy) {
51
+ ${S1} const qiankunLifeCycle = window.proxy.qiankunLifeCycles;
52
+ ${S1} if (qiankunLifeCycle) {
53
+ ${S1} window.proxy.vpq_bootstrap((props) => qiankunLifeCycle.bootstrap && qiankunLifeCycle.bootstrap(props));
54
+ ${S1} window.proxy.vpq_mount((props) => qiankunLifeCycle.mount && qiankunLifeCycle.mount(props));
55
+ ${S1} window.proxy.vpq_unmount((props) => qiankunLifeCycle.unmount && qiankunLifeCycle.unmount(props));
56
+ ${S1} window.proxy.vpq_update((props) => qiankunLifeCycle.update && qiankunLifeCycle.update(props));
57
+ ${S1} window.dispatchEvent(new CustomEvent('qiankun:loaded'));
58
+ ${S1} }
59
+ ${S1} }
60
+ ${S1}}).catch((error) => {
61
+ ${S1} console.error(error);
62
+ ${S1} if (error.name === 'TypeError' && error.message && error.message.startsWith('Failed to fetch dynamically imported module:')) {
63
+ ${S1} window.dispatchEvent(new CustomEvent('qiankun:fetchEntryError', { detail: { url: '${url}', error } }));
64
+ ${S1} } else {
65
+ ${S1} window.dispatchEvent(new CustomEvent('qiankun:runtimeError', { detail: { error } }));
66
+ ${S1} }
50
67
  ${S1}});
51
- ${S0}`);
68
+ ${S0}`
69
+ );
70
+ const preloadLinks = $('link[rel="modulepreload"]');
71
+ if (preloadLinks.length) {
72
+ const urls = preloadLinks.map((_, link) => $(link).attr("href")).get();
73
+ const P1 = (0, import_utils.detectIndent)(html, preloadLinks.get(0));
74
+ preloadLinks.last().after(`
75
+ ${P1}<script>
76
+ ${P1} const preloadUrls = [
77
+ ${urls.map((url2) => `${P1} ${(0, import_utils.normalizeUrl)(url2, { changeScriptOrigin })}`).join(",\n")}
78
+ ${P1} ];
79
+ ${P1} preloadUrls.forEach((url) => {
80
+ ${P1} const link = document.createElement('link');
81
+ ${P1} link.rel = 'modulepreload';
82
+ ${P1} link.href = url;
83
+ ${P1} link.crossOrigin = 'anonymous';
84
+ ${P1} document.head.appendChild(link);
85
+ ${P1} });
86
+ ${P1}</script>`);
87
+ const texts = preloadLinks.map((_, link) => {
88
+ var _a2;
89
+ return ((_a2 = link.next) == null ? void 0 : _a2.type) === "text" ? link.next : null;
90
+ });
91
+ texts.remove();
92
+ preloadLinks.remove();
93
+ }
94
+ if (((_b = context.server) == null ? void 0 : _b.config.command) === "serve") {
95
+ const scripts = $("head script[type=module]").toArray();
96
+ const refreshScript = scripts.find((s) => /@react-refresh";$/m.test($(s).html() ?? ""));
97
+ if (refreshScript) {
98
+ const refreshScript$ = $(refreshScript);
99
+ const R1 = (0, import_utils.detectIndent)(html, refreshScript) + (0, import_utils.space)(2);
100
+ const content = refreshScript$.html();
101
+ const regExp = /import\s*{([^}]*)}\s*from\s*"([^"]*@react-refresh)";/m;
102
+ const match = content == null ? void 0 : content.match(regExp);
103
+ if (content && match) {
104
+ const sentence = match[0];
105
+ const imports = match[1];
106
+ const from = match[2];
107
+ const rest = content.replace(sentence, "");
108
+ refreshScript$.removeAttr("type");
109
+ refreshScript$.html(`
110
+ ${R1}import(${(0, import_utils.normalizeUrl)(from, { changeScriptOrigin })}).then(({${imports}}) => {
111
+ ${R1} ${rest.split("\n").map((s) => s.trim()).filter(Boolean).join(`
112
+ ${R1} `)}
113
+ ${R1}});`);
114
+ }
115
+ }
116
+ }
52
117
  const bodyBaseIndent = (0, import_utils.detectIndent)(html, $("body").get(0));
53
118
  const B1 = bodyBaseIndent + (0, import_utils.space)(2);
54
119
  const B2 = B1 + (0, import_utils.space)(2);
55
120
  $("body").append(`
56
121
  ${B1}<script>
57
- ${B2}${createQiankunHelper(appName, { indent: B2 + (0, import_utils.space)(2) }).trim()}
122
+ ${B2}${exportLifeCycles(appName, { indent: B2 })}
58
123
  ${B1}</script>
59
124
  `);
60
125
  const output = $.html();
@@ -67,21 +132,18 @@ ${B1}</script>
67
132
  configureServer(server) {
68
133
  const base = server.config.base;
69
134
  return () => {
70
- const patchFiles = [`${base}@vite/client`];
71
- patchFiles.forEach((file) => {
72
- server.middlewares.use(file, (req, res, next) => {
73
- const end = res.end.bind(res);
74
- res.end = function(chunk, ...rest) {
75
- if (typeof chunk === "string") {
76
- const $ = (0, import_cheerio.load)(chunk);
77
- module2DynamicImport({ $, scriptTag: $(`script[src="${file}"]`).get(0), changeScriptOrigin });
78
- chunk = $.html();
79
- }
80
- end(chunk, ...rest);
81
- return this;
82
- };
83
- next();
84
- });
135
+ server.middlewares.use((req, res, next) => {
136
+ const end = res.end.bind(res);
137
+ res.end = function(chunk, ...rest) {
138
+ if (typeof chunk === "string") {
139
+ const $ = (0, import_cheerio.load)(chunk);
140
+ module2DynamicImport({ $, scriptTag: $(`script[src="${base}@vite/client"]`).get(0), changeScriptOrigin });
141
+ chunk = $.html();
142
+ }
143
+ end(chunk, ...rest);
144
+ return this;
145
+ };
146
+ next();
85
147
  });
86
148
  };
87
149
  }
@@ -94,58 +156,30 @@ function module2DynamicImport(options) {
94
156
  }
95
157
  const script$ = $(scriptTag);
96
158
  const moduleSrc = script$.attr("src");
97
- let appendBase = "''";
98
- if (changeScriptOrigin) {
99
- appendBase = "window.proxy ? window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || '' : ''";
100
- }
101
159
  script$.removeAttr("src");
102
160
  script$.removeAttr("type");
103
161
  const space2 = ident;
104
162
  script$.html(`
105
- ${space2}const publicUrl = ${appendBase};
106
- ${space2}let assetUrl = '${moduleSrc}';
107
- ${space2}if (!assetUrl.match(/^https?/i)) {
108
- ${space2} assetUrl = publicUrl + assetUrl;
109
- ${space2}}
110
- ${space2}import(assetUrl)`);
163
+ ${space2}import(${(0, import_utils.normalizeUrl)(moduleSrc, { changeScriptOrigin })})`);
111
164
  return script$;
112
165
  }
113
- function createImportFinallyResolve(qiankunName, options) {
166
+ function exportLifeCycles(qiankunName, options) {
114
167
  const { indent: space2 = " " } = options ?? {};
115
168
  return `
116
- ${space2}const qiankunLifeCycle = window.moudleQiankunAppLifeCycles && window.moudleQiankunAppLifeCycles['${qiankunName}'];
117
- ${space2}if (qiankunLifeCycle) {
118
- ${space2} window.proxy.vitemount((props) => qiankunLifeCycle.mount(props));
119
- ${space2} window.proxy.viteunmount((props) => qiankunLifeCycle.unmount(props));
120
- ${space2} window.proxy.vitebootstrap(() => qiankunLifeCycle.bootstrap());
121
- ${space2} window.proxy.viteupdate((props) => qiankunLifeCycle.update(props));
122
- ${space2}}
123
- `;
124
- }
125
- function createQiankunHelper(qiankunName, options) {
126
- const { indent: space2 = " " } = options ?? {};
127
- return `
128
- ${space2}const createDeffer = (hookName) => {
129
- ${space2} const d = new Promise((resolve, reject) => {
130
- ${space2} window.proxy && (window.proxy[\`vite\${hookName}\`] = resolve)
169
+ ${space2}const makeLifeCycle = (hookName) => {
170
+ ${space2} const promise = new Promise((resolve, reject) => {
171
+ ${space2} if (window.proxy) {
172
+ ${space2} window.proxy[\`vpq_\${hookName}\`] = resolve;
173
+ ${space2} }
131
174
  ${space2} })
132
- ${space2} return props => d.then(fn => fn(props));
133
- ${space2}}
134
- ${space2}const bootstrap = createDeffer('bootstrap');
135
- ${space2}const mount = createDeffer('mount');
136
- ${space2}const unmount = createDeffer('unmount');
137
- ${space2}const update = createDeffer('update');
138
-
139
- ${space2};(global => {
140
- ${space2} global.qiankunName = '${qiankunName}';
141
- ${space2} global['${qiankunName}'] = {
142
- ${space2} bootstrap,
143
- ${space2} mount,
144
- ${space2} unmount,
145
- ${space2} update
146
- ${space2} };
147
- ${space2}})(window);
148
- `;
175
+ ${space2} return (props) => promise.then(fn => fn(props));
176
+ ${space2}};
177
+ ${space2}window['${qiankunName}'] = {
178
+ ${space2} bootstrap: makeLifeCycle('bootstrap'),
179
+ ${space2} mount: makeLifeCycle('mount'),
180
+ ${space2} unmount: makeLifeCycle('unmount'),
181
+ ${space2} update: makeLifeCycle('update')
182
+ ${space2}};`.trimStart();
149
183
  }
150
184
  var src_default = qiankunPlugin;
151
185
  // Annotate the CommonJS export names for ESM import in node:
package/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["import type { CheerioAPI } from 'cheerio';\nimport { load } from 'cheerio';\nimport type { Element } from 'domhandler';\nimport type { PluginOption } from 'vite';\nimport { detectIndent, space } from './utils';\n\nexport * from './helper';\n\nexport interface MicroOption {\n /**\n * Whether to change the origin of entry script tag for micro frontend. It's useful when the micro\n * frontend is deployed on a different domain or path.\n *\n * > If the origin by the qiankun's default algorithm is not correct for you, please try the\n * > [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @default true\n */\n changeScriptOrigin?: boolean;\n}\ntype PluginFn = (appName: string, pluginOptions?: MicroOption) => PluginOption;\n\n/**\n * Vite plugin for integrating with Qiankun micro frontend.\n *\n * @param appName The name of the Qiankun sub app.\n * @param pluginOptions Options for configuring the micro frontend behavior.\n *\n * > If the micro app is deployed on a different domain or path, you may need to adjust the public\n * > path. Please have a look at the [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @returns A Vite plugin option object.\n */\nconst qiankunPlugin: PluginFn = (appName, pluginOptions = {}) => {\n const { changeScriptOrigin = true } = pluginOptions;\n\n return {\n name: 'vite-plugin-qiankun',\n\n transformIndexHtml(html: string, context) {\n const $ = load(html, { sourceCodeLocationInfo: true });\n const entryScript =\n $('script[entry]').get(0) ?? $('body script[type=module], head script[crossorigin=\"\"]').get(0);\n if (entryScript) {\n const scriptBaseIndent = detectIndent(html, entryScript);\n const S0 = scriptBaseIndent;\n const S1 = scriptBaseIndent + space(2);\n const S2 = S1 + space(2);\n const script$ = module2DynamicImport({\n $,\n scriptTag: entryScript,\n changeScriptOrigin,\n ident: S1,\n });\n script$?.html(`${script$.html()?.trimEnd()}.finally(() => {\n${S2}${createImportFinallyResolve(appName, { indent: S2 }).trim()}\n${S1}});\n${S0}`);\n\n const bodyBaseIndent = detectIndent(html, $('body').get(0));\n const B1 = bodyBaseIndent + space(2);\n const B2 = B1 + space(2);\n $('body').append(`\n${B1}<script>\n${B2}${createQiankunHelper(appName, { indent: B2 + space(2) }).trim()}\n${B1}</script>\n`);\n const output = $.html();\n return output;\n } else {\n console.warn('\\x1b[33m%s\\x1b[0m', '⚠️ Patch for qiankun failed, because the entry script was not found.');\n return html;\n }\n },\n configureServer(server) {\n const base = server.config.base;\n return () => {\n const patchFiles = [`${base}@vite/client`];\n patchFiles.forEach((file) => {\n server.middlewares.use(file, (req, res, next) => {\n const end = res.end.bind(res);\n res.end = function (this: typeof res, chunk: unknown, ...rest: any[]) {\n if (typeof chunk === 'string') {\n const $ = load(chunk);\n module2DynamicImport({ $, scriptTag: $(`script[src=\"${file}\"]`).get(0), changeScriptOrigin });\n chunk = $.html();\n }\n end(chunk, ...rest);\n return this;\n } as unknown as typeof res.end;\n next();\n });\n });\n };\n },\n };\n};\n\nfunction module2DynamicImport(\n options: { $: CheerioAPI; scriptTag: Element | undefined; ident?: string } & Pick<MicroOption, 'changeScriptOrigin'>,\n) {\n const { $, scriptTag, changeScriptOrigin, ident = '' } = options;\n if (!scriptTag) {\n return;\n }\n const script$ = $(scriptTag);\n const moduleSrc = script$.attr('src');\n let appendBase = \"''\";\n if (changeScriptOrigin) {\n appendBase = \"window.proxy ? window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || '' : ''\";\n }\n script$.removeAttr('src');\n script$.removeAttr('type');\n const space = ident;\n script$.html(`\n${space}const publicUrl = ${appendBase};\n${space}let assetUrl = '${moduleSrc}';\n${space}if (!assetUrl.match(/^https?/i)) {\n${space} assetUrl = publicUrl + assetUrl;\n${space}}\n${space}import(assetUrl)`);\n return script$;\n}\n\nfunction createImportFinallyResolve(qiankunName: string, options?: { indent?: string }) {\n const { indent: space = ' ' } = options ?? {};\n return `\n${space}const qiankunLifeCycle = window.moudleQiankunAppLifeCycles && window.moudleQiankunAppLifeCycles['${qiankunName}'];\n${space}if (qiankunLifeCycle) {\n${space} window.proxy.vitemount((props) => qiankunLifeCycle.mount(props));\n${space} window.proxy.viteunmount((props) => qiankunLifeCycle.unmount(props));\n${space} window.proxy.vitebootstrap(() => qiankunLifeCycle.bootstrap());\n${space} window.proxy.viteupdate((props) => qiankunLifeCycle.update(props));\n${space}}\n`;\n}\n\nfunction createQiankunHelper(qiankunName: string, options?: { indent?: string }) {\n const { indent: space = ' ' } = options ?? {};\n return `\n${space}const createDeffer = (hookName) => {\n${space} const d = new Promise((resolve, reject) => {\n${space} window.proxy && (window.proxy[\\`vite\\${hookName}\\`] = resolve)\n${space} })\n${space} return props => d.then(fn => fn(props));\n${space}}\n${space}const bootstrap = createDeffer('bootstrap');\n${space}const mount = createDeffer('mount');\n${space}const unmount = createDeffer('unmount');\n${space}const update = createDeffer('update');\n\n${space};(global => {\n${space} global.qiankunName = '${qiankunName}';\n${space} global['${qiankunName}'] = {\n${space} bootstrap,\n${space} mount,\n${space} unmount,\n${space} update\n${space} };\n${space}})(window);\n`;\n}\n\nexport default qiankunPlugin;\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAAqB;AAGrB,mBAAoC;AAEpC,wBAAc,qBANd;AAiCA,IAAM,gBAA0B,CAAC,SAAS,gBAAgB,CAAC,MAAM;AAC/D,QAAM,EAAE,qBAAqB,KAAK,IAAI;AAEtC,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,mBAAmB,MAAc,SAAS;AAvC9C;AAwCM,YAAM,QAAI,qBAAK,MAAM,EAAE,wBAAwB,KAAK,CAAC;AACrD,YAAM,cACJ,EAAE,eAAe,EAAE,IAAI,CAAC,KAAK,EAAE,uDAAuD,EAAE,IAAI,CAAC;AAC/F,UAAI,aAAa;AACf,cAAM,uBAAmB,2BAAa,MAAM,WAAW;AACvD,cAAM,KAAK;AACX,cAAM,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cheerio';\nimport { load } from 'cheerio';\nimport type { Element } from 'domhandler';\nimport type { PluginOption } from 'vite';\nimport { detectIndent, normalizeUrl, space } from './utils';\n\nexport * from './helper';\n\nexport interface MicroOption {\n /**\n * Whether to change the origin of entry script tag for micro frontend. It's useful when the micro\n * frontend is deployed on a different domain or path.\n *\n * > If the origin by the qiankun's default algorithm is not correct for you, please try the\n * > [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @default true\n */\n changeScriptOrigin?: boolean;\n}\ntype PluginFn = (appName: string, pluginOptions?: MicroOption) => PluginOption;\n\n/**\n * Vite plugin for integrating with Qiankun micro frontend.\n *\n * @param appName The name of the Qiankun sub app.\n * @param pluginOptions Options for configuring the micro frontend behavior.\n *\n * > If the micro app is deployed on a different domain or path, you may need to adjust the public\n * > path. Please have a look at the [getPublicPath](https://qiankun.umijs.org/zh/api) option.\n *\n * @returns A Vite plugin option object.\n */\nconst qiankunPlugin: PluginFn = (appName, pluginOptions = {}) => {\n const { changeScriptOrigin = true } = pluginOptions;\n\n return {\n name: 'vite-plugin-qiankun',\n\n transformIndexHtml(html: string, context) {\n const $ = load(html, { sourceCodeLocationInfo: true });\n // Transform entry script\n const entryScript =\n $('script[entry]').get(0) ?? $('body script[type=module], head script[crossorigin=\"\"]').get(0);\n if (entryScript) {\n const url = entryScript.attribs.src;\n const scriptBaseIndent = detectIndent(html, entryScript);\n const S0 = scriptBaseIndent;\n const S1 = scriptBaseIndent + space(2);\n const script$ = module2DynamicImport({\n $,\n scriptTag: entryScript,\n changeScriptOrigin,\n ident: S1,\n });\n script$?.html(\n `${script$.html()?.trimEnd()}.then(() => {\n${S1} if (window.proxy) {\n${S1} const qiankunLifeCycle = window.proxy.qiankunLifeCycles;\n${S1} if (qiankunLifeCycle) {\n${S1} window.proxy.vpq_bootstrap((props) => qiankunLifeCycle.bootstrap && qiankunLifeCycle.bootstrap(props));\n${S1} window.proxy.vpq_mount((props) => qiankunLifeCycle.mount && qiankunLifeCycle.mount(props));\n${S1} window.proxy.vpq_unmount((props) => qiankunLifeCycle.unmount && qiankunLifeCycle.unmount(props));\n${S1} window.proxy.vpq_update((props) => qiankunLifeCycle.update && qiankunLifeCycle.update(props));\n${S1} window.dispatchEvent(new CustomEvent('qiankun:loaded'));\n${S1} }\n${S1} }\n${S1}}).catch((error) => {\n${S1} console.error(error);\n${S1} if (error.name === 'TypeError' && error.message && error.message.startsWith('Failed to fetch dynamically imported module:')) {\n${S1} window.dispatchEvent(new CustomEvent('qiankun:fetchEntryError', { detail: { url: '${url}', error } }));\n${S1} } else {\n${S1} window.dispatchEvent(new CustomEvent('qiankun:runtimeError', { detail: { error } }));\n${S1} }\n${S1}});\n${S0}`,\n );\n\n // Transform modulepreload links\n const preloadLinks = $('link[rel=\"modulepreload\"]');\n if (preloadLinks.length) {\n const urls = preloadLinks.map((_, link) => $(link).attr('href')).get();\n const P1 = detectIndent(html, preloadLinks.get(0));\n preloadLinks.last().after(`\n${P1}<script>\n${P1} const preloadUrls = [\n${urls.map((url) => `${P1} ${normalizeUrl(url, { changeScriptOrigin })}`).join(',\\n')}\n${P1} ];\n${P1} preloadUrls.forEach((url) => {\n${P1} const link = document.createElement('link');\n${P1} link.rel = 'modulepreload';\n${P1} link.href = url;\n${P1} link.crossOrigin = 'anonymous';\n${P1} document.head.appendChild(link);\n${P1} });\n${P1}</script>`);\n const texts = preloadLinks.map((_, link) => (link.next?.type === 'text' ? link.next : null));\n texts.remove();\n preloadLinks.remove();\n }\n\n // Transform @react-refresh script\n if (context.server?.config.command === 'serve') {\n const scripts = $('head script[type=module]').toArray();\n const refreshScript = scripts.find((s) => /@react-refresh\";$/m.test($(s).html() ?? ''));\n if (refreshScript) {\n const refreshScript$ = $(refreshScript);\n const R1 = detectIndent(html, refreshScript) + space(2);\n const content = refreshScript$.html();\n const regExp = /import\\s*{([^}]*)}\\s*from\\s*\"([^\"]*@react-refresh)\";/m;\n const match = content?.match(regExp);\n if (content && match) {\n const sentence = match[0];\n const imports = match[1];\n const from = match[2];\n const rest = content.replace(sentence, '');\n refreshScript$.removeAttr('type');\n refreshScript$.html(`\n${R1}import(${normalizeUrl(from, { changeScriptOrigin })}).then(({${imports}}) => {\n${R1} ${rest\n .split('\\n')\n .map((s) => s.trim())\n .filter(Boolean)\n .join(`\\n${R1} `)}\n${R1}});`);\n }\n }\n }\n\n // Add extra script to export lifecycles\n const bodyBaseIndent = detectIndent(html, $('body').get(0));\n const B1 = bodyBaseIndent + space(2);\n const B2 = B1 + space(2);\n $('body').append(`\n${B1}<script>\n${B2}${exportLifeCycles(appName, { indent: B2 })}\n${B1}</script>\n`);\n const output = $.html();\n return output;\n } else {\n console.warn('\\x1b[33m%s\\x1b[0m', '⚠️ Patch for qiankun failed, because the entry script was not found.');\n return html;\n }\n },\n configureServer(server) {\n const base = server.config.base;\n return () => {\n // Only apply to / i.e. the mount point of the app\n server.middlewares.use((req, res, next) => {\n const end = res.end.bind(res);\n res.end = function (this: typeof res, chunk: unknown, ...rest: any[]) {\n if (typeof chunk === 'string') {\n const $ = load(chunk);\n module2DynamicImport({ $, scriptTag: $(`script[src=\"${base}@vite/client\"]`).get(0), changeScriptOrigin });\n chunk = $.html();\n }\n end(chunk, ...rest);\n return this;\n } as unknown as typeof res.end;\n next();\n });\n };\n },\n };\n};\n\nfunction module2DynamicImport(\n options: { $: CheerioAPI; scriptTag: Element | undefined; ident?: string } & Pick<MicroOption, 'changeScriptOrigin'>,\n) {\n const { $, scriptTag, changeScriptOrigin, ident = '' } = options;\n if (!scriptTag) {\n return;\n }\n const script$ = $(scriptTag);\n const moduleSrc = script$.attr('src');\n script$.removeAttr('src');\n script$.removeAttr('type');\n const space = ident;\n script$.html(`\n${space}import(${normalizeUrl(moduleSrc, { changeScriptOrigin })})`);\n return script$;\n}\n\nfunction exportLifeCycles(qiankunName: string, options?: { indent?: string }) {\n const { indent: space = ' ' } = options ?? {};\n return `\n${space}const makeLifeCycle = (hookName) => {\n${space} const promise = new Promise((resolve, reject) => {\n${space} if (window.proxy) {\n${space} window.proxy[\\`vpq_\\${hookName}\\`] = resolve;\n${space} }\n${space} })\n${space} return (props) => promise.then(fn => fn(props));\n${space}};\n${space}window['${qiankunName}'] = {\n${space} bootstrap: makeLifeCycle('bootstrap'),\n${space} mount: makeLifeCycle('mount'),\n${space} unmount: makeLifeCycle('unmount'),\n${space} update: makeLifeCycle('update')\n${space}};`.trimStart();\n}\n\nexport default qiankunPlugin;\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,qBAAqB;AAGrB,mBAAkD;AAElD,wBAAc,qBANd;AAiCA,IAAM,gBAA0B,CAAC,SAAS,gBAAgB,CAAC,MAAM;AAC/D,QAAM,EAAE,qBAAqB,KAAK,IAAI;AAEtC,SAAO;AAAA,IACL,MAAM;AAAA,IAEN,mBAAmB,MAAc,SAAS;AAvC9C;AAwCM,YAAM,QAAI,qBAAK,MAAM,EAAE,wBAAwB,KAAK,CAAC;AAErD,YAAM,cACJ,EAAE,eAAe,EAAE,IAAI,CAAC,KAAK,EAAE,uDAAuD,EAAE,IAAI,CAAC;AAC/F,UAAI,aAAa;AACf,cAAM,MAAM,YAAY,QAAQ;AAChC,cAAM,uBAAmB,2BAAa,MAAM,WAAW;AACvD,cAAM,KAAK;AACX,cAAM,KAAK,uBAAmB,oBAAM,CAAC;AACrC,cAAM,UAAU,qBAAqB;AAAA,UACnC;AAAA,UACA,WAAW;AAAA,UACX;AAAA,UACA,OAAO;AAAA,QACT,CAAC;AACD,2CAAS;AAAA,UACP,IAAG,aAAQ,KAAK,MAAb,mBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,2FAA2F;AAAA,EAC3F;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAIM,cAA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EAAE,GAAG,WAAW,oBAAoB,QAAQ,GAAG,IAAI;AACzD,MAAI,CAAC,WAAW;AACd;AAAA,EACF;AACA,QAAM,UAAU,EAAE,SAAS;AAC3B,QAAM,YAAY,QAAQ,KAAK,KAAK;AACpC,UAAQ,WAAW,KAAK;AACxB,UAAQ,WAAW,MAAM;AACzB,QAAMC,SAAQ;AACd,UAAQ,KAAK;AAAA,EACbA,oBAAe,2BAAa,WAAW,EAAE,mBAAmB,CAAC,IAAI;AACjE,SAAO;AACT;AAEA,SAAS,iBAAiB,aAAqB,SAA+B;AAC5E,QAAM,EAAE,QAAQA,SAAQ,SAAS,IAAI,WAAW,CAAC;AACjD,SAAO;AAAA,EACPA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA,iBAAgB;AAAA,EAChBA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA;AAAA,EACAA,WAAU,UAAU;AACtB;AAEA,IAAO,cAAQ;",
6
+ "names": ["url", "_a", "space"]
7
7
  }
package/lib/utils.d.ts CHANGED
@@ -1,3 +1,6 @@
1
1
  import type { Element } from 'domhandler';
2
- export declare function detectIndent(html: string, entryScript: Element | undefined): string;
2
+ export declare function detectIndent(html: string, element: Element | undefined): string;
3
3
  export declare function space(num: number): string;
4
+ export declare function normalizeUrl(url: string | undefined, options?: {
5
+ changeScriptOrigin?: boolean;
6
+ }): string;
package/lib/utils.js CHANGED
@@ -20,23 +20,24 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var utils_exports = {};
21
21
  __export(utils_exports, {
22
22
  detectIndent: () => detectIndent,
23
+ normalizeUrl: () => normalizeUrl,
23
24
  space: () => space
24
25
  });
25
26
  module.exports = __toCommonJS(utils_exports);
26
- function detectIndent(html, entryScript) {
27
+ function detectIndent(html, element) {
27
28
  let baseIndent = "";
28
- if (entryScript == null ? void 0 : entryScript.sourceCodeLocation) {
29
+ if (element == null ? void 0 : element.sourceCodeLocation) {
29
30
  const newline = html.includes("\r\n") ? "\r\n" : "\n";
30
31
  const lines = html.split(newline);
31
- const lineStr = lines[entryScript.sourceCodeLocation.startLine - 1];
32
+ const lineStr = lines[element.sourceCodeLocation.startLine - 1];
32
33
  if (lineStr) {
33
- const startTag = "<script";
34
+ const startTag = `<${element.tagName}`;
34
35
  const tagNameFromHtml = lineStr.substring(
35
- entryScript.sourceCodeLocation.startCol - 1,
36
- entryScript.sourceCodeLocation.startCol - 1 + startTag.length
36
+ element.sourceCodeLocation.startCol - 1,
37
+ element.sourceCodeLocation.startCol - 1 + startTag.length
37
38
  );
38
39
  if (tagNameFromHtml === startTag) {
39
- for (let i = 0; i < entryScript.sourceCodeLocation.startCol - 1; i++) {
40
+ for (let i = 0; i < element.sourceCodeLocation.startCol - 1; i++) {
40
41
  if (/\s/.test(lineStr[i])) {
41
42
  baseIndent += lineStr[i];
42
43
  } else {
@@ -51,9 +52,18 @@ function detectIndent(html, entryScript) {
51
52
  function space(num) {
52
53
  return new Array(num + 1).join(" ");
53
54
  }
55
+ function normalizeUrl(url, options) {
56
+ const { changeScriptOrigin = true } = options ?? {};
57
+ let appendBase = "''";
58
+ if (changeScriptOrigin) {
59
+ appendBase = "window.proxy && window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || ''";
60
+ }
61
+ return (url == null ? void 0 : url.match(/^https?/i)) ? `'${url}'` : `(${appendBase}) + '${url}'`;
62
+ }
54
63
  // Annotate the CommonJS export names for ESM import in node:
55
64
  0 && (module.exports = {
56
65
  detectIndent,
66
+ normalizeUrl,
57
67
  space
58
68
  });
59
69
  //# sourceMappingURL=utils.js.map
package/lib/utils.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/utils.ts"],
4
- "sourcesContent": ["import type { Element } from 'domhandler';\n\nexport function detectIndent(html: string, entryScript: Element | undefined) {\n let baseIndent = '';\n if (entryScript?.sourceCodeLocation) {\n const newline = html.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lines = html.split(newline);\n const lineStr = lines[entryScript.sourceCodeLocation.startLine - 1];\n if (lineStr) {\n const startTag = '<script';\n const tagNameFromHtml = lineStr.substring(\n entryScript.sourceCodeLocation.startCol - 1,\n entryScript.sourceCodeLocation.startCol - 1 + startTag.length,\n );\n if (tagNameFromHtml === startTag) {\n for (let i = 0; i < entryScript.sourceCodeLocation.startCol - 1; i++) {\n if (/\\s/.test(lineStr[i])) {\n baseIndent += lineStr[i];\n } else {\n break;\n }\n }\n }\n }\n }\n return baseIndent;\n}\n\nexport function space(num: number) {\n return new Array(num + 1).join(' ');\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,SAAS,aAAa,MAAc,aAAkC;AAC3E,MAAI,aAAa;AACjB,MAAI,2CAAa,oBAAoB;AACnC,UAAM,UAAU,KAAK,SAAS,MAAM,IAAI,SAAS;AACjD,UAAM,QAAQ,KAAK,MAAM,OAAO;AAChC,UAAM,UAAU,MAAM,YAAY,mBAAmB,YAAY,CAAC;AAClE,QAAI,SAAS;AACX,YAAM,WAAW;AACjB,YAAM,kBAAkB,QAAQ;AAAA,QAC9B,YAAY,mBAAmB,WAAW;AAAA,QAC1C,YAAY,mBAAmB,WAAW,IAAI,SAAS;AAAA,MACzD;AACA,UAAI,oBAAoB,UAAU;AAChC,iBAAS,IAAI,GAAG,IAAI,YAAY,mBAAmB,WAAW,GAAG,KAAK;AACpE,cAAI,KAAK,KAAK,QAAQ,CAAC,CAAC,GAAG;AACzB,0BAAc,QAAQ,CAAC;AAAA,UACzB,OAAO;AACL;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,MAAM,KAAa;AACjC,SAAO,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,GAAG;AACpC;",
4
+ "sourcesContent": ["import type { Element } from 'domhandler';\n\nexport function detectIndent(html: string, element: Element | undefined) {\n let baseIndent = '';\n if (element?.sourceCodeLocation) {\n const newline = html.includes('\\r\\n') ? '\\r\\n' : '\\n';\n const lines = html.split(newline);\n const lineStr = lines[element.sourceCodeLocation.startLine - 1];\n if (lineStr) {\n const startTag = `<${element.tagName}`;\n const tagNameFromHtml = lineStr.substring(\n element.sourceCodeLocation.startCol - 1,\n element.sourceCodeLocation.startCol - 1 + startTag.length,\n );\n if (tagNameFromHtml === startTag) {\n for (let i = 0; i < element.sourceCodeLocation.startCol - 1; i++) {\n if (/\\s/.test(lineStr[i])) {\n baseIndent += lineStr[i];\n } else {\n break;\n }\n }\n }\n }\n }\n return baseIndent;\n}\n\nexport function space(num: number) {\n return new Array(num + 1).join(' ');\n}\n\nexport function normalizeUrl(url: string | undefined, options?: { changeScriptOrigin?: boolean }) {\n const { changeScriptOrigin = true } = options ?? {};\n let appendBase = \"''\";\n if (changeScriptOrigin) {\n appendBase = \"window.proxy && window.proxy.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ || ''\";\n }\n return url?.match(/^https?/i) ? `'${url}'` : `(${appendBase}) + '${url}'`;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,SAAS,aAAa,MAAc,SAA8B;AACvE,MAAI,aAAa;AACjB,MAAI,mCAAS,oBAAoB;AAC/B,UAAM,UAAU,KAAK,SAAS,MAAM,IAAI,SAAS;AACjD,UAAM,QAAQ,KAAK,MAAM,OAAO;AAChC,UAAM,UAAU,MAAM,QAAQ,mBAAmB,YAAY,CAAC;AAC9D,QAAI,SAAS;AACX,YAAM,WAAW,IAAI,QAAQ;AAC7B,YAAM,kBAAkB,QAAQ;AAAA,QAC9B,QAAQ,mBAAmB,WAAW;AAAA,QACtC,QAAQ,mBAAmB,WAAW,IAAI,SAAS;AAAA,MACrD;AACA,UAAI,oBAAoB,UAAU;AAChC,iBAAS,IAAI,GAAG,IAAI,QAAQ,mBAAmB,WAAW,GAAG,KAAK;AAChE,cAAI,KAAK,KAAK,QAAQ,CAAC,CAAC,GAAG;AACzB,0BAAc,QAAQ,CAAC;AAAA,UACzB,OAAO;AACL;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,MAAM,KAAa;AACjC,SAAO,IAAI,MAAM,MAAM,CAAC,EAAE,KAAK,GAAG;AACpC;AAEO,SAAS,aAAa,KAAyB,SAA4C;AAChG,QAAM,EAAE,qBAAqB,KAAK,IAAI,WAAW,CAAC;AAClD,MAAI,aAAa;AACjB,MAAI,oBAAoB;AACtB,iBAAa;AAAA,EACf;AACA,UAAO,2BAAK,MAAM,eAAc,IAAI,SAAS,IAAI,kBAAkB;AACrE;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiny-codes/vite-plugin-qiankun",
3
- "version": "2.0.0",
3
+ "version": "2.0.2",
4
4
  "description": "vite for qiankun. This is a forked version of vite-plugin-qiankun.",
5
5
  "keywords": [
6
6
  "qiankun",
@@ -61,7 +61,8 @@
61
61
  "vite": "^2.9.9"
62
62
  },
63
63
  "peerDependencies": {
64
- "vite": "^2.0.0 | ^3.0.0 | ^4.0.0 | ^5.0.0 | ^6.0.0 | ^7.0.0 | ^8.0.0"
64
+ "rolldown": "^1.0.0-rc.9",
65
+ "vite": ">=8.0.0"
65
66
  },
66
67
  "publishConfig": {
67
68
  "registry": "https://registry.npmjs.org/"
package/readme.md CHANGED
@@ -1,84 +1,71 @@
1
- #### 简介
1
+ ## 简介
2
2
 
3
- forked from [vite-plugin-qiankun](https://github.com/tengmaoqing/vite-plugin-qiankun)
4
-
5
- > vite-plugin-qiankun: 帮助应用快速接入乾坤的vite插件
3
+ > `@tiny-codes/vite-plugin-qiankun`: 帮助应用快速接入乾坤的vite插件
6
4
 
7
5
  - 保留vite构建es模块的优势
8
6
  - 一键配置,不影响已有的vite配置
9
7
  - 支持vite开发环境
10
8
 
11
- #### 快速开始
9
+ Forked from [vite-plugin-qiankun](https://github.com/tengmaoqing/vite-plugin-qiankun)
10
+
11
+ ## 快速开始
12
12
 
13
- ###### 1、在 `vite.config.ts` 中安装插件
13
+ ### 1、在 `vite.config.ts` 中安装插件
14
14
 
15
15
  ```typescript
16
16
  // vite.config.ts
17
- import qiankun from 'vite-plugin-qiankun';
17
+ import qiankun from '@tiny-codes/vite-plugin-qiankun';
18
18
 
19
19
  export default {
20
- // 这里的 'myMicroAppName' 是子应用名,主应用注册时AppName需保持一致
21
- plugins: [qiankun('myMicroAppName')],
22
- // 生产环境需要指定运行域名作为base
23
- base: 'http://xxx.com/',
20
+ // 这里的 subApp 是子应用名,主应用注册时 name 需保持一致
21
+ plugins: [
22
+ // ...
23
+ qiankun('subApp'),
24
+ ],
24
25
  };
25
26
  ```
26
27
 
27
- ###### 2、在入口文件里面写入乾坤的生命周期配置
28
+ ### 2、在入口文件里面写入乾坤的生命周期配置
28
29
 
29
- ```typescript
30
+ ```ts
30
31
  // main.ts
31
- import { qiankunWindow, renderWithQiankun } from 'vite-plugin-qiankun';
32
+ import { qiankunWindow, exportQiankunLifeCycles } from '@tiny-codes/vite-plugin-qiankun';
32
33
 
33
- // some code
34
- renderWithQiankun({
35
- mount(props) {
36
- console.log('mount');
37
- render(props);
38
- },
39
- bootstrap() {
40
- console.log('bootstrap');
41
- },
42
- unmount(props: any) {
43
- console.log('unmount');
44
- const { container } = props;
45
- const mountRoot = container?.querySelector('#root');
46
- ReactDOM.unmountComponentAtNode(mountRoot || document.querySelector('#root'));
47
- },
48
- });
34
+ const root = createRoot(document.getElementById('root'));
49
35
 
50
- if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
51
- render({});
36
+ if (qiankunWindow.__POWERED_BY_QIANKUN__) {
37
+ exportQiankunLifeCycles({
38
+ bootstrap(props) {
39
+ console.log('bootstrap');
40
+ },
41
+ mount(props) {
42
+ console.log('mount');
43
+ root.render(<App/>);
44
+ },
45
+ unmount(props) {
46
+ console.log('unmount');
47
+ root.unmount();
48
+ },
49
+ update(props) {
50
+ console.log('update', props);
51
+ }
52
+ });
53
+ }
54
+ else {
55
+ root.render(<App/>);
52
56
  }
53
- ```
54
-
55
- ###### 3、dev下作为子应用调试
56
-
57
- > 因为开发环境作为子应用时与热更新插件(可能与其他修改html的插件也会存在冲突)有冲突,所以需要额外的调试配置
58
-
59
- ```typescript
60
- // useDevMode 开启时与热更新插件冲突,使用变量切换
61
- const useDevMode = true;
62
57
 
63
- const baseConfig: UserConfig = {
64
- plugins: [
65
- ...(useDevMode ? [] : [reactRefresh()]),
66
- qiankun('viteapp', {
67
- useDevMode,
68
- }),
69
- ],
70
- };
71
58
  ```
72
59
 
73
- 上面例子中 `useDevMode = true` 则不使用热更新插件,`useDevMode = false` 则能使用热更新,但无法作为子应用加载。
74
-
75
- ###### 4、子应用部署的域名不同
60
+ ### 3、子应用部署到不同的域名
76
61
 
77
- 如果子应用与主应用部署的域名不同,并且子应用的`base`使用了相对路径,例如`/sub-app`,此时可能会导致子应用入口script加载失败。在子应用的页面里,入口script可能会是`/sub-app/index.js`,qiankun会尝试加载该路径,但由于当前域名是主应用,就会导致浏览器尝试从主应用的域名下去加载资源,肯定会失败。
62
+ 如果子应用与主应用部署的域名不同,并且子应用的`base`是相对路径(例如`/sub-app/`),此时很可能子应用会加载失败。子应用的入口 script 标签可能类似于 `/sub-app/index.js`,qiankun会尝试在主应用域名下加载该资源,当然会失败。
78
63
 
79
- 要解决这个问题,可以使用 [getPublicPath](https://qiankun.umijs.org/zh/api) 选项,返回子应用的域名。
64
+ 要解决这个问题,可以使用 [getPublicPath](https://qiankun.umijs.org/zh/api) 选项,返回子应用的域名,注意末尾不要包含`/`。
80
65
 
81
66
  ```tsx
67
+ import { loadMicroApp } from 'qiankun';
68
+
82
69
  loadMicroApp(
83
70
  {
84
71
  name: 'sub-app',
@@ -90,21 +77,52 @@ loadMicroApp(
90
77
  );
91
78
  ```
92
79
 
93
- ###### 5、其它使用注意点 `qiankunWindow`
80
+ ### 4、显式指定入口文件
81
+
82
+ qiankun会默认取最后一个 `script` 标签作为子应用的入口文件,但如果由于特殊原因不能把入口文件放到最后,也可以显式指定入口文件,在script标签上添加 `entry` 属性即可,详情参考[官方文档](https://qiankun.umijs.org/zh/faq)。
94
83
 
95
- 因为es模块加载与`qiankun`的实现方式有些冲突,所以使用本插件实现的`qiankun`微应用里面没有运行在js沙盒中。所以在不可避免需要设置window上的属性时,尽量显示的操作js沙盒,否则可能会对其它子应用产生副作用。qiankun沙盒使用方式
84
+ ### 5、全局事件
85
+
86
+ 本插件会在子应用加载完成后触发 `qiankun:loaded` 事件,在子应用入口脚本加载失败时触发 `qiankun:fetchEntryError` 事件,在子应用运行时发生错误时触发 `qiankun:runtimeError` 事件。可以通过监听这些事件来处理相应的逻辑,或在页面上显示相应的操作提示。
96
87
 
97
88
  ```typescript
98
- import { qiankunWindow } from 'vite-plugin-qiankun';
89
+ window.addEventListener('qiankun:loaded', () => {
90
+ console.log('The sub-application has been loaded successfully.');
91
+ });
99
92
 
100
- qiankunWindow.customxxx = 'ssss';
93
+ window.addEventListener('qiankun:fetchEntryError', (event) => {
94
+ console.error('The sub-application entry script failed to load', event.detail);
95
+ document.querySelector('#root').innerHTML = `
96
+ If the main application is hosted on a different domain, make sure getPublicPath is configured to return the domain of sub app. For example:
97
+ <pre>
98
+ loadMicroApp({
99
+ name: "subApp",
100
+ entry: 'https://domain-to-subApp/pages'
101
+ }, {
102
+ getPublicPath: () => "https://domain-to-subApp"
103
+ });
104
+ </pre>`;
105
+ });
106
+
107
+ window.addEventListener('qiankun:runtimeError', (event) => {
108
+ console.error('The sub-application runtime error occurred', event.detail);
109
+ });
110
+ ```
111
+
112
+ ### 6、其它使用注意点 `qiankunWindow`
113
+
114
+ 因为 esm 模块加载与`qiankun`的实现方式有些冲突,所以使用本插件实现的`qiankun`微应用里面没有运行在js沙盒中。所以在不可避免需要设置window上的属性时,尽量显式地操作js沙盒,否则可能会对其它子应用产生副作用。qiankun沙盒对象的使用方式:
115
+
116
+ ```typescript
117
+ import { qiankunWindow } from '@tiny-codes/vite-plugin-qiankun';
101
118
 
102
119
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
103
- console.log('我正在作为子应用运行');
120
+ console.log('I am running as a sub-application');
104
121
  }
122
+ qiankunWindow.foo = 'bar';
105
123
  ```
106
124
 
107
- #### 例子
125
+ ## 例子
108
126
 
109
127
  详细的信息可以参考例子里面的使用方式
110
128