@lark-apaas/miaoda-presets 1.0.0 → 1.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.
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ /**
3
+ * 错误容器组件
4
+ * @param {*} document
5
+ * @param {*} root
6
+ * @param {object} props
7
+ * @param {string} props.errorMessage - 错误信息
8
+ * @param {function} props.onRepairClick - 修复按钮点击事件
9
+ * @param {function} props.onCopyClick - 复制按钮点击事件
10
+ */
11
+ function ErrorContainer(document, root, props) {
12
+ // 创建容器元素
13
+ const container = document.createElement('div');
14
+ container.className = 'container';
15
+ // 创建内容元素
16
+ const content = document.createElement('div');
17
+ content.className = 'content';
18
+ container.appendChild(content);
19
+ // 创建图片元素
20
+ const img = document.createElement('img');
21
+ img.src =
22
+ 'https://lf3-static.bytednsdoc.com/obj/eden-cn/ylcylz_fsph_ryhs/ljhwZthlaukjlkulzlp/feisuda/template/render_error.svg';
23
+ img.alt = 'render error';
24
+ // 图片占位
25
+ img.width = 120;
26
+ img.height = 120;
27
+ img.className = 'error-image';
28
+ content.appendChild(img);
29
+ // 创建标题元素
30
+ const title = document.createElement('p');
31
+ title.className = 'title';
32
+ title.textContent = '哎呀,写错代码了';
33
+ content.appendChild(title);
34
+ // 创建描述元素
35
+ const description = document.createElement('p');
36
+ description.className = 'description';
37
+ description.textContent = '可复制错误信息,或告诉妙搭进行修复。';
38
+ content.appendChild(description);
39
+ // 创建按钮组元素
40
+ const buttonGroup = document.createElement('div');
41
+ buttonGroup.className = 'button-group';
42
+ content.appendChild(buttonGroup);
43
+ // 创建复制按钮
44
+ const copyBtn = document.createElement('button');
45
+ copyBtn.className = 'button button-copy';
46
+ copyBtn.id = 'copyBtn';
47
+ copyBtn.textContent = '复制错误信息';
48
+ copyBtn.addEventListener('click', props.onCopyClick);
49
+ buttonGroup.appendChild(copyBtn);
50
+ // 创建修复按钮
51
+ const repairBtn = document.createElement('button');
52
+ repairBtn.className = 'button button-repair';
53
+ repairBtn.id = 'repairBtn';
54
+ repairBtn.textContent = '告诉妙搭修复';
55
+ repairBtn.addEventListener('click', props.onRepairClick);
56
+ buttonGroup.appendChild(repairBtn);
57
+ // 添加到根元素
58
+ root.appendChild(container);
59
+ }
60
+ function RootStyle(document, root) {
61
+ const style = document.createElement('style');
62
+ style.id = 'react-refresh-overlay-style';
63
+ style.textContent = `
64
+ * {
65
+ margin: 0;
66
+ padding: 0;
67
+ box-sizing: border-box;
68
+ }
69
+
70
+ body {
71
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
72
+ 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
73
+ sans-serif;
74
+ -webkit-font-smoothing: antialiased;
75
+ -moz-osx-font-smoothing: grayscale;
76
+ }
77
+
78
+ .container {
79
+ min-height: 100vh;
80
+ display: flex;
81
+ align-items: center;
82
+ justify-content: center;
83
+ background-color: #F3F4F6; /* bg-gray-100 */
84
+ }
85
+
86
+ .content {
87
+ display: flex;
88
+ flex-direction: column;
89
+ justify-content: center;
90
+ align-items: center;
91
+ text-align: center;
92
+ }
93
+
94
+ .error-image {
95
+ margin-bottom: 16px; /* mb-4 */
96
+ width: 120px; /* w-[120px] */
97
+ height: auto;
98
+ }
99
+
100
+ .title {
101
+ font-size: 18px; /* text-l (推测为 text-lg) */
102
+ line-height: 22px;
103
+ color: #1F2329;
104
+ font-weight: 500; /* font-medium */
105
+ margin-bottom: 8px; /* mb-2 */
106
+ }
107
+
108
+ .description {
109
+ font-size: 14px; /* text-sm */
110
+ line-height: 22px;
111
+ color: #646A73;
112
+ font-weight: 400; /* font-normal */
113
+ margin-bottom: 8px; /* mb-2 */
114
+ }
115
+
116
+ .button-group {
117
+ display: flex;
118
+ gap: 16px; /* space-x-4 */
119
+ }
120
+
121
+ .button {
122
+ height: 32px; /* h-[32px] */
123
+ padding: 0 16px;
124
+ border-radius: 6px; /* rounded-[6px] */
125
+ font-size: 14px; /* text-sm */
126
+ font-weight: 400; /* font-[400] */
127
+ cursor: pointer;
128
+ transition: all 0.2s;
129
+ outline: none; /* focus:outline-hidden */
130
+ border: 1px solid;
131
+ }
132
+
133
+ .button-copy {
134
+ background-color: white; /* bg-white */
135
+ color: #4B5563; /* text-gray-600 */
136
+ border-color: #D0D3D6; /* border-[#D0D3D6] */
137
+ box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); /* shadow-xs */
138
+ }
139
+
140
+ .button-copy:hover {
141
+ background-color: #F3F4F6; /* hover:bg-gray-100 */
142
+ }
143
+
144
+ .button-copy:active {
145
+ background-color: #E5E7EB; /* active:bg-gray-200 */
146
+ }
147
+
148
+ .button-repair {
149
+ background-color: #2563EB; /* bg-blue-600 */
150
+ color: white; /* text-white */
151
+ border-color: transparent; /* border-transparent */
152
+ font-weight: 500; /* font-medium */
153
+ box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06); /* shadow-xs */
154
+ }
155
+
156
+ .button-repair:hover {
157
+ background-color: #2563EB; /* hover:bg-blue-600 (保持不变) */
158
+ }
159
+
160
+ .button-repair:active {
161
+ background-color: #1E40AF; /* active:bg-blue-700 */
162
+ }
163
+ `;
164
+ root.appendChild(style);
165
+ }
166
+ module.exports = {
167
+ ErrorContainer,
168
+ RootStyle,
169
+ };
@@ -0,0 +1,330 @@
1
+ "use strict";
2
+ /* eslint-disable no-undef */
3
+ const { ErrorContainer, RootStyle } = require('./components');
4
+ /* ===== Cached elements for DOM manipulations ===== */
5
+ /**
6
+ * The iframe that contains the overlay.
7
+ * @type {HTMLIFrameElement}
8
+ */
9
+ let iframeRoot = null;
10
+ /**
11
+ * The document object from the iframe root, used to create and render elements.
12
+ * @type {Document}
13
+ */
14
+ let rootDocument = null;
15
+ /**
16
+ * The root div elements will attach to.
17
+ * @type {HTMLDivElement}
18
+ */
19
+ let root = null;
20
+ /**
21
+ * A Cached function to allow deferred render.
22
+ * @type {RenderFn | null}
23
+ */
24
+ let scheduledRenderFn = null;
25
+ /* ===== Overlay State ===== */
26
+ /**
27
+ * The latest error message from Webpack compilation.
28
+ * @type {string}
29
+ */
30
+ let currentCompileErrorMessage = '';
31
+ /**
32
+ * The latest runtime error objects.
33
+ * @type {Error[]}
34
+ */
35
+ let currentRuntimeErrors = [];
36
+ /**
37
+ * The render mode the overlay is currently in.
38
+ * @type {'compileError' | 'runtimeError' | null}
39
+ */
40
+ let currentMode = null;
41
+ /**
42
+ * @typedef {Object} IframeProps
43
+ * @property {function(): void} onIframeLoad
44
+ */
45
+ /**
46
+ * Creates the main `iframe` the overlay will attach to.
47
+ * Accepts a callback to be ran after iframe is initialized.
48
+ * @param {Document} document
49
+ * @param {HTMLElement} root
50
+ * @param {IframeProps} props
51
+ * @returns {HTMLIFrameElement}
52
+ */
53
+ function IframeRoot(document, root, props) {
54
+ const iframe = document.createElement('iframe');
55
+ iframe.id = 'react-refresh-overlay';
56
+ iframe.src = 'about:blank';
57
+ iframe.style.border = 'none';
58
+ iframe.style.height = '100%';
59
+ iframe.style.left = '0';
60
+ iframe.style.minHeight = '100vh';
61
+ iframe.style.minHeight = '-webkit-fill-available';
62
+ iframe.style.position = 'fixed';
63
+ iframe.style.top = '0';
64
+ iframe.style.width = '100vw';
65
+ iframe.style.zIndex = '2147483647';
66
+ iframe.addEventListener('load', function onLoad() {
67
+ // Reset margin of iframe body
68
+ iframe.contentDocument.body.style.margin = '0';
69
+ props.onIframeLoad();
70
+ });
71
+ // We skip mounting and returns as we need to ensure
72
+ // the load event is fired after we setup the global variable
73
+ return iframe;
74
+ }
75
+ /**
76
+ * Creates the main `div` element for the overlay to render.
77
+ * @param {Document} document
78
+ * @param {HTMLElement} root
79
+ * @returns {HTMLDivElement}
80
+ */
81
+ function OverlayRoot(document, root) {
82
+ const div = document.createElement('div');
83
+ div.id = 'container';
84
+ root.appendChild(div);
85
+ return div;
86
+ }
87
+ /**
88
+ * Ensures the iframe root and the overlay root are both initialized before render.
89
+ * If check fails, render will be deferred until both roots are initialized.
90
+ * @param {RenderFn} renderFn A function that triggers a DOM render.
91
+ * @returns {void}
92
+ */
93
+ function ensureRootExists(renderFn) {
94
+ if (root) {
95
+ // Overlay root is ready, we can render right away.
96
+ renderFn();
97
+ return;
98
+ }
99
+ // Creating an iframe may be asynchronous so we'll defer render.
100
+ // In case of multiple calls, function from the last call will be used.
101
+ scheduledRenderFn = renderFn;
102
+ if (iframeRoot) {
103
+ // Iframe is already ready, it will fire the load event.
104
+ return;
105
+ }
106
+ // Create the iframe root, and, the overlay root inside it when it is ready.
107
+ iframeRoot = IframeRoot(document, document.body, {
108
+ onIframeLoad: function onIframeLoad() {
109
+ rootDocument = iframeRoot.contentDocument;
110
+ RootStyle(rootDocument, rootDocument.head);
111
+ root = OverlayRoot(rootDocument, rootDocument.body);
112
+ scheduledRenderFn();
113
+ },
114
+ });
115
+ // We have to mount here to ensure `iframeRoot` is set when `onIframeLoad` fires.
116
+ // This is because onIframeLoad() will be called synchronously
117
+ // or asynchronously depending on the browser.
118
+ document.body.appendChild(iframeRoot);
119
+ }
120
+ function removeAllChildren(element, skip) {
121
+ /** @type {Node[]} */
122
+ const childList = Array.prototype.slice.call(element.childNodes, typeof skip !== 'undefined' ? skip : 0);
123
+ for (let i = 0; i < childList.length; i += 1) {
124
+ element.removeChild(childList[i]);
125
+ }
126
+ }
127
+ async function copyToClipboard(text) {
128
+ try {
129
+ // 优先使用现代的 Clipboard API
130
+ if (navigator.clipboard && window.isSecureContext) {
131
+ await navigator.clipboard.writeText(text);
132
+ return true;
133
+ }
134
+ // 降级方案:使用传统的 execCommand 方法
135
+ return fallbackCopyToClipboard(text);
136
+ }
137
+ catch (error) {
138
+ console.error('复制到剪切板失败:', error);
139
+ return false;
140
+ }
141
+ }
142
+ // 获取父窗口 origin
143
+ function getPreviewParentOrigin() {
144
+ const { origin } = window.location;
145
+ // 线上环境
146
+ if (origin.includes('feishuapp.cn') ||
147
+ origin.includes('miaoda.feishuapp.net')) {
148
+ return 'https://miaoda.feishu.cn';
149
+ }
150
+ // PRE 环境
151
+ if (origin.includes('fsapp.kundou.cn') ||
152
+ origin.includes('miaoda-pre.feishuapp.net')) {
153
+ return 'https://miaoda.feishu-pre.cn';
154
+ }
155
+ // BOE 环境
156
+ return 'https://miaoda.feishu-boe.cn';
157
+ }
158
+ /**
159
+ * Creates the main `div` element for the overlay to render.
160
+ * @returns {void}
161
+ */
162
+ function render() {
163
+ ensureRootExists(function () {
164
+ removeAllChildren(root);
165
+ // 发送 postMessage
166
+ const sendPostMessage = (message, targetOrigin) => {
167
+ const origin = targetOrigin || getPreviewParentOrigin();
168
+ window.parent.postMessage(message, origin);
169
+ };
170
+ if (currentCompileErrorMessage) {
171
+ currentMode = 'compileError';
172
+ ErrorContainer(rootDocument, root, {
173
+ errorMessage: currentCompileErrorMessage,
174
+ onRepairClick: function onRepairClick() {
175
+ sendPostMessage({
176
+ type: 'RenderErrorRepair',
177
+ data: currentCompileErrorMessage,
178
+ });
179
+ },
180
+ onCopyClick: function onCopyClick() {
181
+ copyToClipboard(currentCompileErrorMessage);
182
+ },
183
+ });
184
+ }
185
+ else if (currentRuntimeErrors.length) {
186
+ currentMode = 'runtimeError';
187
+ let errors = '';
188
+ currentRuntimeErrors.forEach(error => {
189
+ errors += `${error.message}\n${error.stack}\n`;
190
+ });
191
+ // 叠加全部报错,将报错信息发送到妙搭
192
+ ErrorContainer(rootDocument, root, {
193
+ errorMessage: errors,
194
+ onRepairClick: function onRepairClick() {
195
+ sendPostMessage({
196
+ type: 'RenderErrorRepair',
197
+ data: errors,
198
+ });
199
+ },
200
+ onCopyClick: function onCopyClick() {
201
+ copyToClipboard(errors);
202
+ },
203
+ });
204
+ }
205
+ });
206
+ }
207
+ /**
208
+ * Destroys the state of the overlay.
209
+ * @returns {void}
210
+ */
211
+ function cleanup() {
212
+ // Clean up and reset all internal state.
213
+ try {
214
+ document.body.removeChild(iframeRoot);
215
+ }
216
+ catch (e) {
217
+ // In case user render react app directly to body, will trigger `NotFoundError` when recovery from an Error
218
+ // https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild#exceptions
219
+ }
220
+ scheduledRenderFn = null;
221
+ root = null;
222
+ iframeRoot = null;
223
+ }
224
+ /**
225
+ * Clears Webpack compilation errors and dismisses the compile error overlay.
226
+ * @returns {void}
227
+ */
228
+ function clearCompileError() {
229
+ if (!root || currentMode !== 'compileError') {
230
+ return;
231
+ }
232
+ currentCompileErrorMessage = '';
233
+ currentMode = null;
234
+ cleanup();
235
+ }
236
+ /**
237
+ * Clears runtime error records and dismisses the runtime error overlay.
238
+ * @param {boolean} [dismissOverlay] Whether to dismiss the overlay or not.
239
+ * @returns {void}
240
+ */
241
+ function clearRuntimeErrors(dismissOverlay) {
242
+ if (!root || currentMode !== 'runtimeError') {
243
+ return;
244
+ }
245
+ currentRuntimeErrors = [];
246
+ if (typeof dismissOverlay === 'undefined' || dismissOverlay) {
247
+ currentMode = null;
248
+ cleanup();
249
+ }
250
+ }
251
+ /**
252
+ * Shows the compile error overlay with the specific Webpack error message.
253
+ * @param {string} message
254
+ * @returns {void}
255
+ */
256
+ function showCompileError(message) {
257
+ if (!message) {
258
+ return;
259
+ }
260
+ currentCompileErrorMessage = message;
261
+ render();
262
+ }
263
+ /**
264
+ * Shows the runtime error overlay with the specific error records.
265
+ * @param {Error[]} errors
266
+ * @returns {void}
267
+ */
268
+ function showRuntimeErrors(errors) {
269
+ if (!errors || !errors.length) {
270
+ return;
271
+ }
272
+ currentRuntimeErrors = errors;
273
+ render();
274
+ }
275
+ function debounce(fn, wait) {
276
+ /**
277
+ * A cached setTimeout handler.
278
+ * @type {number | undefined}
279
+ */
280
+ let timer;
281
+ /**
282
+ * @returns {void}
283
+ */
284
+ function debounced() {
285
+ const context = this;
286
+ const args = arguments;
287
+ clearTimeout(timer);
288
+ timer = setTimeout(function () {
289
+ return fn.apply(context, args);
290
+ }, wait);
291
+ }
292
+ return debounced;
293
+ }
294
+ /**
295
+ * The debounced version of `showRuntimeErrors` to prevent frequent renders
296
+ * due to rapid firing listeners.
297
+ * @param {Error[]} errors
298
+ * @returns {void}
299
+ */
300
+ const debouncedShowRuntimeErrors = debounce(showRuntimeErrors, 30);
301
+ /**
302
+ * Detects if an error is a Webpack compilation error.
303
+ * @param {Error} error The error of interest.
304
+ * @returns {boolean} If the error is a Webpack compilation error.
305
+ */
306
+ function isWebpackCompileError(error) {
307
+ return (/Module [A-z ]+\(from/.test(error.message) ||
308
+ /Cannot find module/.test(error.message));
309
+ }
310
+ /**
311
+ * Handles runtime error contexts captured with EventListeners.
312
+ * Integrates with a runtime error overlay.
313
+ * @param {Error} error A valid error object.
314
+ * @returns {void}
315
+ */
316
+ function handleRuntimeError(error) {
317
+ if (error &&
318
+ !isWebpackCompileError(error) &&
319
+ currentRuntimeErrors.indexOf(error) === -1) {
320
+ currentRuntimeErrors = currentRuntimeErrors.concat(error);
321
+ }
322
+ debouncedShowRuntimeErrors(currentRuntimeErrors);
323
+ }
324
+ module.exports = Object.freeze({
325
+ clearCompileError: clearCompileError,
326
+ clearRuntimeErrors: clearRuntimeErrors,
327
+ handleRuntimeError: handleRuntimeError,
328
+ showCompileError: showCompileError,
329
+ showRuntimeErrors: showRuntimeErrors,
330
+ });
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+ const ReactRefreshPlugin = require('@rspack/plugin-react-refresh');
3
+ const path = require('path');
4
+ function createReactRefreshPlugin() {
5
+ return new ReactRefreshPlugin({
6
+ overlay: {
7
+ module: path.resolve(__dirname, 'overlay/index.js'),
8
+ },
9
+ });
10
+ }
11
+ module.exports = createReactRefreshPlugin;
@@ -27,17 +27,30 @@ exports.default = {
27
27
  'import/named': 'error', // 检查命名导入是否存在
28
28
  // 效果相关:模型不会
29
29
  'no-constant-binary-expression': 'off', // 不强制使用常量二进制表达式
30
- // 效果相关:希望模型使用内置 logger
31
30
  'no-restricted-syntax': [
32
31
  'error',
32
+ // 效果相关:希望模型使用内置 logger 而不是 console
33
33
  {
34
34
  selector: "CallExpression[callee.object.name='console'][callee.property.name=/^(log|warn|info|debug|trace)$/]",
35
35
  message: 'Avoid using console.log, console.warn, etc. Use `@byted/spark-framework/logger` instead.',
36
36
  },
37
+ // 禁用BOM方法alert和confirm,及不推荐使用同名方法
38
+ {
39
+ message: "Please don't use window.alert, use `Dialog` component instead for better user experience and consistency",
40
+ selector: "MemberExpression[object.name='window'][property.name='alert']",
41
+ },
37
42
  {
38
43
  message: "Please don't use window.confirm, use `Dialog` component instead for better user experience and consistency",
39
44
  selector: "MemberExpression[object.name='window'][property.name='confirm']",
40
45
  },
46
+ {
47
+ message: "Please don't use alert. It may conflict with window.alert BOM method, use `Dialog` component instead for better user experience and consistency",
48
+ selector: "CallExpression[callee.name='alert']",
49
+ },
50
+ {
51
+ message: "Please don't use confirm. It may conflict with window.confirm BOM method, use `Dialog` component instead for better user experience and consistency",
52
+ selector: "CallExpression[callee.name='confirm']",
53
+ },
41
54
  ],
42
55
  },
43
56
  };
@@ -8,6 +8,8 @@ const path_1 = __importDefault(require("path"));
8
8
  const core_1 = __importDefault(require("@rspack/core"));
9
9
  // eslint-disable-next-line @typescript-eslint/no-var-requires
10
10
  const RouteParserPlugin = require('../rspack-plugins/route-parser-plugin');
11
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
12
+ const SlardarPerformanceMonitorPlugin = require('../rspack-plugins/slardar-performance-monitor-plugin');
11
13
  // eslint-disable-next-line max-lines-per-function
12
14
  function createRecommendRspackConfig(options) {
13
15
  const { enableReactRefresh = false, isDev = true, needRoutes = true, runtimeMode = 'fullstack', } = options;
@@ -120,6 +122,8 @@ function createRecommendRspackConfig(options) {
120
122
  new core_1.default.optimize.LimitChunkCountPlugin({
121
123
  maxChunks: 1,
122
124
  }),
125
+ // 全栈模式下,增加性能监控上报脚本注入
126
+ runtimeMode === 'fullstack' ? new SlardarPerformanceMonitorPlugin() : undefined,
123
127
  // 开发环境下,解析路由
124
128
  isDev &&
125
129
  needRoutes &&
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ /**
3
+ * 加载性能监控脚本
4
+ * @param {object} option
5
+ * @param {string} [option.bid='apaas_ai']
6
+ * @param {string} [option.globalName='KSlardarWeb']
7
+ * @returns
8
+ */
9
+ function getSlardarScript(option = {}) {
10
+ const bid = option.bid || 'apaas_ai';
11
+ const globalName = option.globalName || 'KSlardarWeb';
12
+ return `
13
+ <script>
14
+ // 创建 Slardar 脚本元素
15
+ const slardarScript = document.createElement('script');
16
+ slardarScript.src = 'https://lf3-short.ibytedapm.com/slardar/fe/sdk-web/browser.cn.js?bid=${bid}&globalName=${globalName}';
17
+ slardarScript.crossOrigin = 'anonymous';
18
+
19
+ // 添加 onload 事件处理
20
+ slardarScript.onload = function() {
21
+ // 脚本加载完成后执行初始化
22
+ if (window.KSlardarWeb) {
23
+ window.KSlardarWeb('init', {
24
+ bid: 'apaas_ai',
25
+ // 四种类型:dev/boe/pre/online
26
+ env: 'online',
27
+ });
28
+ window.KSlardarWeb('start');
29
+ }
30
+ };
31
+
32
+ // 添加错误处理
33
+ slardarScript.onerror = function() {
34
+ console.warn('Failed to load Slardar script');
35
+ };
36
+
37
+ // 将脚本添加到页面
38
+ document.head.appendChild(slardarScript);
39
+
40
+ // 添加 TTI 监控脚本
41
+ const performanceScript = document.createElement('script');
42
+ performanceScript.src = 'https://sf3-scmcdn-cn.feishucdn.com/obj/unpkg/byted/performance/0.1.0/dist/performance.iife.js';
43
+ document.head.appendChild(performanceScript);
44
+ </script>
45
+
46
+ `;
47
+ }
48
+ class SlardarPerformanceMonitorPlugin {
49
+ constructor(options) {
50
+ this.options = options || {};
51
+ }
52
+ apply(compiler) {
53
+ compiler.hooks.compilation.tap('SlardarPerformanceMonitorPlugin', compilation => {
54
+ try {
55
+ // 尝试获取HtmlRspackPlugin的hooks
56
+ let HtmlPlugin;
57
+ try {
58
+ HtmlPlugin = require('@rspack/core').rspack.HtmlRspackPlugin;
59
+ }
60
+ catch (e) {
61
+ // 如果html-rspack-plugin不可用,尝试使用html-webpack-plugin
62
+ try {
63
+ HtmlPlugin = require('html-webpack-plugin');
64
+ }
65
+ catch (e2) {
66
+ console.warn('SlardarPerformanceMonitorPlugin: html-rspack-plugin or html-webpack-plugin not found');
67
+ return;
68
+ }
69
+ }
70
+ const hooks = HtmlPlugin.getHooks(compilation);
71
+ // 在生成 HTML 前修改内容
72
+ hooks.beforeEmit.tapAsync('SlardarPerformanceMonitorPlugin', (data, cb) => {
73
+ const position = this.options.position ?? 'head-end';
74
+ const snippet = this.options.snippet ?? getSlardarScript();
75
+ if (!snippet)
76
+ return;
77
+ if (position === 'body-end') {
78
+ data.html = data.html.replace('</body>', `${snippet}\n</body>`);
79
+ }
80
+ else if (position === 'body-start') {
81
+ data.html = data.html.replace('<body>', `<body>\n${snippet}`);
82
+ }
83
+ else if (position === 'head-end') {
84
+ data.html = data.html.replace('</head>', `${snippet}\n</head>`);
85
+ }
86
+ cb(null, data);
87
+ });
88
+ }
89
+ catch (error) {
90
+ console.error('Error in SlardarPerformanceMonitorPlugin:', error);
91
+ }
92
+ });
93
+ }
94
+ }
95
+ // 导出插件
96
+ module.exports = SlardarPerformanceMonitorPlugin;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/miaoda-presets",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "files": [
5
5
  "lib"
6
6
  ],