@unpackjs/plugin-react 3.3.3 → 3.4.0

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/dist/index.js CHANGED
@@ -1,61 +1,19 @@
1
1
  import __rslib_shim_module__ from 'module';
2
2
  let require = __rslib_shim_module__.createRequire(import.meta.url);
3
3
  import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
4
- import plugin_react_refresh from "@rspack/plugin-react-refresh";
5
- import { TEMPLATE_CONTENT, addRestartCleaner, colors, esVersionToBrowserslist, getPathInJs, getPort, isDev, isDevServer, isFunction, isPlainObject, launchEditor, logger, mergeConfig as core_mergeConfig, removeDir, rspack } from "@unpackjs/core";
4
+ import node_path, { dirname as __rspack_dirname } from "node:path";
6
5
  import node_fs from "node:fs";
7
- import node_http from "node:http";
8
- var click_to_component_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
9
- let applyClickToComponentConfig = async ({ config, unpackConfig, cachePath })=>{
10
- let { port } = await new Promise((resolve)=>{
11
- let server = node_http.createServer((req, res)=>{
12
- let params = new URLSearchParams(req.url.slice(1)), file = decodeURIComponent(params.get('file')), line = Number(params.get('line')), column = Number(params.get('column'));
13
- res.writeHead(200, {
14
- 'Access-Control-Allow-Origin': '*',
15
- 'Access-Control-Allow-Methods': '*',
16
- 'Access-Control-Allow-Headers': '*',
17
- 'Access-Control-Allow-Private-Network': 'true'
18
- }), res.end('ok'), launchEditor(`${file}:${line}:${column}`);
19
- });
20
- getPort().then((port)=>{
21
- server.listen(port, ()=>{
22
- resolve({
23
- port
24
- });
25
- });
26
- }), addRestartCleaner(()=>new Promise((resolve)=>server.close(()=>resolve())));
27
- }), injectScript = node_fs.readFileSync(node_path.resolve(click_to_component_dirname, './injectScript.js'), 'utf-8'), scriptTpl = `
28
- if (!document.querySelector('#__click-to-component__')) {
29
- const script = document.createElement('script')
30
- window['CLICK_TO_COMPONENT'] = { port: ${port} }
31
- script.setAttribute('type', 'text/javascript')
32
- script.textContent = \`${injectScript}\`
33
- document.body.appendChild(script)
34
- }`;
35
- if (unpackConfig.mpa) Object.values(config.entry).forEach((entryConfig)=>{
36
- let filePath = entryConfig.import[0], content = node_fs.readFileSync(filePath, 'utf-8');
37
- node_fs.writeFileSync(filePath, `${scriptTpl}\n${content}`, 'utf-8');
38
- });
39
- else {
40
- let realEntryPath = node_path.resolve(config.context, cachePath, 'entries', `index.${port}.jsx`), tpl = `
41
- ${scriptTpl}
42
- import '${getPathInJs(node_path.resolve(Object.values(config.entry)[0]))}'
43
- `, dir = node_path.dirname(realEntryPath);
44
- node_fs.existsSync(dir) || node_fs.mkdirSync(dir, {
45
- recursive: !0
46
- }), node_fs.writeFileSync(realEntryPath, tpl, 'utf-8'), config.entry = {
47
- main: realEntryPath
48
- };
49
- }
50
- return config;
51
- }, PLUGIN_NAME = 'unpack:react', pluginReact = (options = {})=>{
6
+ import plugin_react_refresh from "@rspack/plugin-react-refresh";
7
+ import { JSX_REGEX, JS_REGEX, SCRIPT_REGEX, esVersionToBrowserslist, getHtmlTemplateOrContent, getPathInJs, injectToHead, isDevServer, isFunction, isPlainObject, launchEditor, mergeConfig as core_mergeConfig, removeDir, rspack } from "@unpackjs/core";
8
+ var src_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
9
+ let pluginReact = (options = {})=>{
52
10
  let { clickToComponent } = options;
53
11
  return {
54
- name: PLUGIN_NAME,
12
+ name: 'unpack:react',
55
13
  bundlerConfig: async (originalConfig, { unpackConfig, mergeConfig, cachePath })=>{
56
14
  let config = originalConfig;
57
15
  unpackConfig.mpa && (config = (({ config, unpackConfig, cachePath })=>{
58
- let start, entry, html, pagesRoot, tempDirectory = node_path.join(cachePath, 'mpa'), userOptions = isPlainObject(unpackConfig.mpa) ? unpackConfig.mpa : {}, { entry: entry1, html: html1 } = (start = performance.now(), entry = {}, html = [], pagesRoot = node_path.join(unpackConfig.root, 'src', 'pages'), node_fs.readdirSync(pagesRoot).forEach((filename)=>{
16
+ let entry, html, pagesRoot, tempDirectory = node_path.join(cachePath, 'mpa'), userOptions = isPlainObject(unpackConfig.mpa) ? unpackConfig.mpa : {}, { template, templateContent } = getHtmlTemplateOrContent(unpackConfig.html?.template, unpackConfig.root), { entry: entry1, html: html1 } = (entry = {}, html = [], pagesRoot = node_path.join(unpackConfig.root, 'src', 'pages'), node_fs.readdirSync(pagesRoot).forEach((filename)=>{
59
17
  if (filename.startsWith('.')) return;
60
18
  let indexFilePath = ((dir)=>{
61
19
  for (let extension of [
@@ -68,32 +26,27 @@ import '${getPathInJs(node_path.resolve(Object.values(config.entry)[0]))}'
68
26
  return null;
69
27
  })(node_path.join(pagesRoot, filename));
70
28
  if (indexFilePath) {
71
- let filePath, pageConfig, pageConfig1 = (filePath = node_path.join(indexFilePath, '../config.json'), pageConfig = {}, node_fs.existsSync(filePath) && (pageConfig = JSON.parse(node_fs.readFileSync(filePath, 'utf-8'))), pageConfig), entryName = !0 === userOptions.lowerCase ? filename.toLowerCase() : filename;
72
- pageConfig1.filename && (entryName = pageConfig1.filename.slice(0, -5)), entry[entryName] = {
29
+ let entryName = !0 === userOptions.lowerCase ? filename.toLowerCase() : filename;
30
+ entry[entryName] = {
73
31
  import: [
74
32
  indexFilePath
75
33
  ]
76
- }, pageConfig1.template && (pageConfig1.template = node_path.join(indexFilePath, '../', pageConfig1.template)), html.push({
77
- template: unpackConfig.html?.template || void 0,
78
- templateContent: unpackConfig.html?.templateContent || (unpackConfig.html?.template ? void 0 : TEMPLATE_CONTENT),
79
- minify: !1,
34
+ }, html.push({
80
35
  filename: `${entryName}.html`,
81
36
  chunks: [
82
37
  entryName
83
38
  ],
84
- ...pageConfig1,
85
39
  templateParameters: {
86
40
  mountId: unpackConfig.html?.mountId || '',
87
41
  title: isFunction(unpackConfig.html?.title) ? unpackConfig.html?.title({
88
42
  entryName
89
43
  }) : unpackConfig.html?.title || '',
90
44
  headTag: unpackConfig.html?.headTag || '',
91
- ...unpackConfig.html?.templateParameters,
92
- ...pageConfig1.templateParameters
45
+ ...unpackConfig.html?.templateParameters
93
46
  }
94
47
  });
95
48
  }
96
- }), isDevServer() || logger.info(`collect entries in ${(performance.now() - start).toFixed(2)}ms ${colors.dim('[MPA]')}`), {
49
+ }), {
97
50
  entry,
98
51
  html
99
52
  });
@@ -115,16 +68,17 @@ ${renderer}
115
68
  }), node_fs.writeFileSync(filePath, tpl, 'utf-8'), entryConfig.import[0] = filePath;
116
69
  }), entry;
117
70
  })(entry1),
118
- plugins: html1.map((h)=>new rspack.HtmlRspackPlugin(h))
71
+ plugins: html1.map((h)=>new rspack.HtmlRspackPlugin({
72
+ ...h,
73
+ template,
74
+ templateContent,
75
+ minify: !1
76
+ }))
119
77
  });
120
78
  })({
121
79
  config,
122
80
  unpackConfig,
123
81
  cachePath
124
- })), isDev() && clickToComponent && (config = await applyClickToComponentConfig({
125
- config,
126
- unpackConfig,
127
- cachePath
128
82
  }));
129
83
  let jsExclude = [
130
84
  /node_modules[\\/](?!\.unpack)/
@@ -152,7 +106,7 @@ ${renderer}
152
106
  module: {
153
107
  rules: [
154
108
  {
155
- test: /\.(j|t)s$/,
109
+ test: JS_REGEX,
156
110
  exclude: jsExclude,
157
111
  use: [
158
112
  {
@@ -164,7 +118,7 @@ ${renderer}
164
118
  ]
165
119
  },
166
120
  {
167
- test: /\.(j|t)sx$/,
121
+ test: JSX_REGEX,
168
122
  exclude: jsExclude,
169
123
  use: [
170
124
  {
@@ -182,7 +136,7 @@ ${renderer}
182
136
  },
183
137
  {
184
138
  test: /\.svg$/i,
185
- issuer: /\.[jt]sx?$/,
139
+ issuer: SCRIPT_REGEX,
186
140
  resourceQuery: {
187
141
  not: [
188
142
  /url/
@@ -205,8 +159,24 @@ ${renderer}
205
159
  }
206
160
  }
207
161
  });
162
+ },
163
+ setupMiddlewares: (middlewares)=>isDevServer() && clickToComponent ? [
164
+ (req, res, next)=>{
165
+ if (!req.url) return void next();
166
+ let url = new URL(req.url, 'http://localhost');
167
+ if ('/__click_to_component__' !== url.pathname) return void next();
168
+ let file = url.searchParams.get('file'), line = Number(url.searchParams.get('line')), column = Number(url.searchParams.get('column'));
169
+ res.writeHead(200, {
170
+ 'Content-Type': 'text/plain'
171
+ }), res.end('ok'), launchEditor(`${decodeURIComponent(file)}:${line}:${column}`);
172
+ },
173
+ ...middlewares
174
+ ] : middlewares,
175
+ transformHtml: (html)=>{
176
+ if (!isDevServer() || !clickToComponent) return html;
177
+ let injectScriptPath = node_path.resolve(src_dirname, 'injectScript.js'), injectScript = node_fs.readFileSync(injectScriptPath, 'utf-8');
178
+ return injectToHead(html, `<script>${injectScript}</script>`);
208
179
  }
209
180
  };
210
181
  };
211
- import node_path, { dirname as __rspack_dirname } from "node:path";
212
- export { PLUGIN_NAME, pluginReact };
182
+ export { pluginReact };
@@ -1,4 +1,4 @@
1
- !function() {
1
+ (()=>{
2
2
  let cover = null, nameTag = null, currentDebugSource = null, cachedFiberKey = null, isEnabled = !1, debounceTimer = null;
3
3
  function applyStyles(target, styles) {
4
4
  for(let key in styles)target.style[key] = styles[key];
@@ -9,7 +9,7 @@
9
9
  let handleClick = (e)=>{
10
10
  0 === e.button && (e.preventDefault(), e.stopPropagation(), function() {
11
11
  if (!currentDebugSource) return;
12
- let port = window.CLICK_TO_COMPONENT?.port, { fileName, lineNumber, columnNumber } = currentDebugSource, url = new URL('http://localhost:' + port + '/');
12
+ let { fileName, lineNumber, columnNumber } = currentDebugSource, url = new URL('/__click_to_component__', window.location.origin);
13
13
  url.searchParams.set('file', fileName), url.searchParams.set('line', lineNumber), url.searchParams.set('column', columnNumber), fetch(url.toString()).catch(()=>{
14
14
  new Image().src = url.toString();
15
15
  });
@@ -24,7 +24,7 @@
24
24
  if (!target || 'object' != typeof target) return null;
25
25
  if (cachedFiberKey && target[cachedFiberKey]) return target[cachedFiberKey];
26
26
  try {
27
- cachedFiberKey = Object.keys(target).find((key)=>key.startsWith('__reactFiber$'));
27
+ cachedFiberKey = Object.keys(target).find((key)=>key.startsWith('__reactFiber'));
28
28
  } catch {
29
29
  return null;
30
30
  }
@@ -114,5 +114,5 @@
114
114
  })));
115
115
  }), document.addEventListener('keyup', (e)=>{
116
116
  ('Alt' === e.key || 'Option' === e.key) && stopInspect();
117
- }), window.addEventListener('blur', stopInspect), console.log('%c[Click-To-Component] Ready.', 'color: #888');
118
- }();
117
+ }), window.addEventListener('blur', stopInspect);
118
+ })();
@@ -1,5 +1,4 @@
1
1
  import { type UnpackPlugin } from '@unpackjs/core';
2
- export declare const PLUGIN_NAME = "unpack:react";
3
2
  export type PluginReactOptions = {
4
3
  clickToComponent?: boolean;
5
4
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAA+C,KAAK,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAI/F,eAAO,MAAM,WAAW,iBAAiB,CAAA;AAEzC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AACD,eAAO,MAAM,WAAW,GAAI,UAAS,kBAAuB,KAAG,YAuF9D,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAQL,KAAK,YAAY,EAClB,MAAM,gBAAgB,CAAA;AAGvB,MAAM,MAAM,kBAAkB,GAAG;IAC/B,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AACD,eAAO,MAAM,WAAW,GAAI,UAAS,kBAAuB,KAAG,YAkH9D,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"mpa.d.ts","sourceRoot":"","sources":["../src/mpa.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,oBAAoB,EAWzB,KAAK,YAAY,EAClB,MAAM,gBAAgB,CAAA;AAYvB,eAAO,MAAM,cAAc,GAAI,sCAI5B;IACD,MAAM,EAAE,oBAAoB,CAAA;IAC5B,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,MAAM,CAAA;CAClB,KAAG,oBA2GH,CAAA"}
1
+ {"version":3,"file":"mpa.d.ts","sourceRoot":"","sources":["../src/mpa.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,KAAK,oBAAoB,EAQzB,KAAK,YAAY,EAClB,MAAM,gBAAgB,CAAA;AASvB,eAAO,MAAM,cAAc,GAAI,sCAI5B;IACD,MAAM,EAAE,oBAAoB,CAAA;IAC5B,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,MAAM,CAAA;CAClB,KAAG,oBA4FH,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unpackjs/plugin-react",
3
- "version": "3.3.3",
3
+ "version": "3.4.0",
4
4
  "description": "React plugin for Unpack",
5
5
  "type": "module",
6
6
  "exports": {
@@ -24,11 +24,11 @@
24
24
  "dependencies": {
25
25
  "@rspack/plugin-react-refresh": "1.5.3",
26
26
  "@svgr/webpack": "8.1.0",
27
- "@swc/helpers": "0.5.17",
27
+ "@swc/helpers": "0.5.18",
28
28
  "react-refresh": "0.18.0"
29
29
  },
30
30
  "devDependencies": {
31
- "@unpackjs/core": "3.7.4"
31
+ "@unpackjs/core": "3.8.0"
32
32
  },
33
33
  "peerDependencies": {
34
34
  "@unpackjs/core": "3.x"
@@ -1,7 +0,0 @@
1
- import { type BundlerConfiguration, type UnpackConfig } from '@unpackjs/core';
2
- export declare const applyClickToComponentConfig: ({ config, unpackConfig, cachePath, }: {
3
- config: BundlerConfiguration;
4
- unpackConfig: UnpackConfig;
5
- cachePath: string;
6
- }) => Promise<BundlerConfiguration>;
7
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/click-to-component/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAEL,KAAK,oBAAoB,EAIzB,KAAK,YAAY,EAClB,MAAM,gBAAgB,CAAA;AA4BvB,eAAO,MAAM,2BAA2B,GAAU,sCAI/C;IACD,MAAM,EAAE,oBAAoB,CAAA;IAC5B,YAAY,EAAE,YAAY,CAAA;IAC1B,SAAS,EAAE,MAAM,CAAA;CAClB,KAAG,OAAO,CAAC,oBAAoB,CA+B/B,CAAA"}