@unpackjs/plugin-react 2.0.0 → 2.1.1

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.cjs CHANGED
@@ -1,92 +1,201 @@
1
1
  "use strict";
2
+ let __rslib_import_meta_url__ = 'undefined' == typeof document ? new (require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
2
3
  var __webpack_require__ = {};
3
- (()=>{
4
- __webpack_require__.n = (module)=>{
5
- var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
- __webpack_require__.d(getter, {
7
- a: getter
8
- });
9
- return getter;
10
- };
11
- })();
12
- (()=>{
13
- __webpack_require__.d = (exports1, definition)=>{
14
- for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
- enumerable: true,
16
- get: definition[key]
17
- });
18
- };
19
- })();
20
- (()=>{
21
- __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
- })();
23
- (()=>{
24
- __webpack_require__.r = (exports1)=>{
25
- if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
- value: 'Module'
27
- });
28
- Object.defineProperty(exports1, '__esModule', {
29
- value: true
30
- });
31
- };
32
- })();
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module.default : ()=>module;
6
+ return __webpack_require__.d(getter, {
7
+ a: getter
8
+ }), getter;
9
+ }, __webpack_require__.d = (exports1, definition)=>{
10
+ for(var key in definition)__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key) && Object.defineProperty(exports1, key, {
11
+ enumerable: !0,
12
+ get: definition[key]
13
+ });
14
+ }, __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop), __webpack_require__.r = (exports1)=>{
15
+ 'undefined' != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports1, Symbol.toStringTag, {
16
+ value: 'Module'
17
+ }), Object.defineProperty(exports1, '__esModule', {
18
+ value: !0
19
+ });
20
+ };
33
21
  var __webpack_exports__ = {};
34
- __webpack_require__.r(__webpack_exports__);
35
- __webpack_require__.d(__webpack_exports__, {
36
- PLUGIN_NAME: ()=>PLUGIN_NAME,
37
- pluginReact: ()=>pluginReact
22
+ __webpack_require__.r(__webpack_exports__), __webpack_require__.d(__webpack_exports__, {
23
+ pluginReact: ()=>pluginReact,
24
+ PLUGIN_NAME: ()=>PLUGIN_NAME
38
25
  });
39
- const external_node_path_namespaceObject = require("node:path");
40
- var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
41
- const react_refresh_webpack_plugin_namespaceObject = require("@pmmmwh/react-refresh-webpack-plugin");
42
- var react_refresh_webpack_plugin_default = /*#__PURE__*/ __webpack_require__.n(react_refresh_webpack_plugin_namespaceObject);
43
- const plugin_react_refresh_namespaceObject = require("@rspack/plugin-react-refresh");
44
- var plugin_react_refresh_default = /*#__PURE__*/ __webpack_require__.n(plugin_react_refresh_namespaceObject);
45
- const core_namespaceObject = require("@unpackjs/core");
46
- const index_cjs_namespaceObject = require("./click-to-component/index.cjs");
47
- const external_mpa_cjs_namespaceObject = require("./mpa.cjs");
48
- const external_splitChunks_cjs_namespaceObject = require("./splitChunks.cjs");
49
- const PLUGIN_NAME = 'unpack:react';
50
- const pluginReact = (options = {})=>{
51
- const { clickToComponent, reactCompiler } = options;
26
+ let external_node_path_namespaceObject = require("node:path");
27
+ var external_node_path_default = __webpack_require__.n(external_node_path_namespaceObject);
28
+ let react_refresh_webpack_plugin_namespaceObject = require("@pmmmwh/react-refresh-webpack-plugin");
29
+ var react_refresh_webpack_plugin_default = __webpack_require__.n(react_refresh_webpack_plugin_namespaceObject);
30
+ let plugin_react_refresh_namespaceObject = require("@rspack/plugin-react-refresh");
31
+ var plugin_react_refresh_default = __webpack_require__.n(plugin_react_refresh_namespaceObject);
32
+ let core_namespaceObject = require("@unpackjs/core"), external_node_fs_namespaceObject = require("node:fs");
33
+ var external_node_fs_default = __webpack_require__.n(external_node_fs_namespaceObject);
34
+ let external_node_http_namespaceObject = require("node:http");
35
+ var external_node_http_default = __webpack_require__.n(external_node_http_namespaceObject);
36
+ let external_launch_editor_namespaceObject = require("launch-editor");
37
+ var external_launch_editor_default = __webpack_require__.n(external_launch_editor_namespaceObject);
38
+ let createServer = ()=>new Promise((resolve)=>{
39
+ let server = external_node_http_default().createServer((req, res)=>{
40
+ let params = new URLSearchParams(req.url.slice(1)), file = decodeURIComponent(params.get('file')), line = Number(params.get('line')), column = Number(params.get('column'));
41
+ res.writeHead(200, {
42
+ 'Access-Control-Allow-Origin': '*',
43
+ 'Access-Control-Allow-Methods': '*',
44
+ 'Access-Control-Allow-Headers': '*',
45
+ 'Access-Control-Allow-Private-Network': 'true'
46
+ }), res.end('ok'), external_launch_editor_default()(`${file}:${line}:${column}`);
47
+ });
48
+ (0, core_namespaceObject.getPort)().then((port)=>{
49
+ server.listen(port, ()=>{
50
+ resolve({
51
+ port
52
+ });
53
+ });
54
+ }), core_namespaceObject.restartCleaners.push(()=>new Promise((resolve)=>server.close(()=>resolve())));
55
+ }), applyClickToComponentConfig = async ({ config, unpackConfig })=>{
56
+ let { port } = await createServer(), injectScript = external_node_fs_default().readFileSync(external_node_path_default().resolve(__dirname, './injectScript.js'), 'utf-8'), scriptTpl = `
57
+ if (!document.querySelector('#__click-to-component__')) {
58
+ const script = document.createElement('script')
59
+ window['CLICK_TO_COMPONENT'] = { port: ${port} }
60
+ script.setAttribute('type', 'text/javascript')
61
+ script.textContent = \`${injectScript}\`
62
+ document.body.appendChild(script)
63
+ }`;
64
+ if (unpackConfig.mpa) Object.values(config.entry).forEach((entryConfig)=>{
65
+ let filePath = entryConfig.import[0], content = external_node_fs_default().readFileSync(filePath, 'utf-8');
66
+ external_node_fs_default().writeFileSync(filePath, `${scriptTpl}\n${content}`, 'utf-8');
67
+ });
68
+ else {
69
+ let realEntryPath = external_node_path_default().resolve(config.context, core_namespaceObject.TEMP_DIR, 'entries', `index.${port}.jsx`), tpl = `
70
+ ${scriptTpl}
71
+ import '${(0, core_namespaceObject.getPathInJs)(external_node_path_default().resolve(Object.values(config.entry)[0]))}'
72
+ `, dir = external_node_path_default().dirname(realEntryPath);
73
+ external_node_fs_default().existsSync(dir) || external_node_fs_default().mkdirSync(dir, {
74
+ recursive: !0
75
+ }), external_node_fs_default().writeFileSync(realEntryPath, tpl, 'utf-8'), config.entry = {
76
+ main: realEntryPath
77
+ };
78
+ }
79
+ return config;
80
+ }, applyMpaConfig = ({ config, unpackConfig, mergeConfig, HtmlPlugin })=>{
81
+ if (!unpackConfig.mpa) return config;
82
+ let isRspack = 'rspack' === unpackConfig.bundler, tempDirectory = external_node_path_default().join(core_namespaceObject.TEMP_DIR, 'mpa'), userOptions = (0, core_namespaceObject.isPlainObject)(unpackConfig.mpa) ? unpackConfig.mpa : {}, { entry, html } = (()=>{
83
+ let start = performance.now(), entry = {}, html = [], pagesRoot = external_node_path_default().join(unpackConfig.root, 'src', 'pages');
84
+ return external_node_fs_default().readdirSync(pagesRoot).forEach((filename)=>{
85
+ if (filename.startsWith('.')) return;
86
+ let indexFilePath = ((dir)=>{
87
+ for (let extension of [
88
+ '.tsx',
89
+ '.jsx'
90
+ ]){
91
+ let indexFilePath = external_node_path_default().join(dir, `index${extension}`);
92
+ if (external_node_fs_default().existsSync(indexFilePath)) return indexFilePath;
93
+ }
94
+ return null;
95
+ })(external_node_path_default().join(pagesRoot, filename));
96
+ if (indexFilePath) {
97
+ var _unpackConfig_html, _unpackConfig_html1, _unpackConfig_html2, _unpackConfig_html3, _unpackConfig_html4, _unpackConfig_html5, _unpackConfig_html6, _unpackConfig_html7, _unpackConfig_html8;
98
+ let pageConfig = ((indexPath)=>{
99
+ let filePath = external_node_path_default().join(indexPath, '../config.json'), pageConfig = {};
100
+ return external_node_fs_default().existsSync(filePath) && (pageConfig = JSON.parse(external_node_fs_default().readFileSync(filePath, 'utf-8'))), pageConfig;
101
+ })(indexFilePath), entryName = !0 === userOptions.lowerCase ? filename.toLowerCase() : filename;
102
+ pageConfig.filename && (entryName = pageConfig.filename.slice(0, -5)), entry[entryName] = {
103
+ import: [
104
+ indexFilePath
105
+ ]
106
+ }, pageConfig.template && (pageConfig.template = external_node_path_default().join(indexFilePath, '../', pageConfig.template)), html.push({
107
+ template: (null == (_unpackConfig_html = unpackConfig.html) ? void 0 : _unpackConfig_html.template) || (isRspack ? void 0 : ''),
108
+ templateContent: (null == (_unpackConfig_html1 = unpackConfig.html) ? void 0 : _unpackConfig_html1.templateContent) || ((null == (_unpackConfig_html2 = unpackConfig.html) ? void 0 : _unpackConfig_html2.template) ? !!isRspack && void 0 : core_namespaceObject.TEMPLATE_CONTENT),
109
+ minify: !1,
110
+ filename: `${entryName}.html`,
111
+ chunks: [
112
+ entryName
113
+ ],
114
+ ...pageConfig,
115
+ templateParameters: {
116
+ mountId: null == (_unpackConfig_html3 = unpackConfig.html) ? void 0 : _unpackConfig_html3.mountId,
117
+ title: (0, core_namespaceObject.isFunction)(null == (_unpackConfig_html4 = unpackConfig.html) ? void 0 : _unpackConfig_html4.title) ? null == (_unpackConfig_html5 = unpackConfig.html) ? void 0 : _unpackConfig_html5.title({
118
+ entryName
119
+ }) : (null == (_unpackConfig_html6 = unpackConfig.html) ? void 0 : _unpackConfig_html6.title) || '',
120
+ headTag: (null == (_unpackConfig_html7 = unpackConfig.html) ? void 0 : _unpackConfig_html7.headTag) || '',
121
+ ...null == (_unpackConfig_html8 = unpackConfig.html) ? void 0 : _unpackConfig_html8.templateParameters,
122
+ ...pageConfig.templateParameters
123
+ }
124
+ });
125
+ }
126
+ }), (0, core_namespaceObject.isDevServer)() || core_namespaceObject.logger.info(`collect entries in ${(performance.now() - start).toFixed(2)}ms ${core_namespaceObject.colors.dim('[MPA]')}`), {
127
+ entry,
128
+ html
129
+ };
130
+ })();
131
+ return config = mergeConfig(config, {
132
+ entry: ((entry)=>{
133
+ var _userOptions_globalImport, _unpackConfig_html;
134
+ let root = unpackConfig.root;
135
+ (0, core_namespaceObject.removeDir)(external_node_path_default().join(root, tempDirectory));
136
+ let globalImport = (null == (_userOptions_globalImport = userOptions.globalImport) ? void 0 : _userOptions_globalImport.reduce((acc, curr)=>`${acc}\nimport '${(0, core_namespaceObject.getPathInJs)(external_node_path_default().resolve(root, curr))}'`, '')) || '', { layout } = userOptions, layoutImport = layout ? `import Layout from '${(0, core_namespaceObject.getPathInJs)(external_node_path_default().resolve(root, layout))}'` : '', layoutJSX = layout ? '<Layout><App /></Layout>' : '<App />', rootElement = `document.getElementById('${null == (_unpackConfig_html = unpackConfig.html) ? void 0 : _unpackConfig_html.mountId}')`, renderer = `ReactDOM.createRoot(${rootElement}).render(${layoutJSX})`;
137
+ return Object.entries(entry).forEach(([entryName, entryConfig])=>{
138
+ let filePath = external_node_path_default().join(root, tempDirectory, `${entryName}.jsx`), tpl = `
139
+ import React from 'react'
140
+ import ReactDOM from 'react-dom/client'
141
+ import App from '${(0, core_namespaceObject.getPathInJs)(entryConfig.import[0])}'${layoutImport && `\n${layoutImport}`}
142
+ ${globalImport}
143
+ ${renderer}
144
+ `, dir = external_node_path_default().dirname(filePath);
145
+ external_node_fs_default().existsSync(dir) || external_node_fs_default().mkdirSync(dir, {
146
+ recursive: !0
147
+ }), external_node_fs_default().writeFileSync(filePath, tpl, 'utf-8'), entryConfig.import[0] = filePath;
148
+ }), entry;
149
+ })(entry),
150
+ plugins: html.map((h)=>new HtmlPlugin(h))
151
+ });
152
+ }, applySplitChunksConfig = ({ config, unpackConfig })=>{
153
+ if ('split-by-experience' !== unpackConfig.performance.chunkSplit.strategy) return config;
154
+ let currentConfig = config.optimization.splitChunks, extraGroups = {};
155
+ return extraGroups.react = {
156
+ name: 'lib-react',
157
+ test: (0, core_namespaceObject.isDevServer)() ? /node_modules[\\/](?:react|react-dom|scheduler|react-refresh|@rspack[\\/]plugin-react-refresh)[\\/]/ : /node_modules[\\/](?:react|react-dom|scheduler)[\\/]/,
158
+ priority: 0
159
+ }, extraGroups.router = {
160
+ name: 'lib-router',
161
+ test: /node_modules[\\/](?:react-router|react-router-dom|history|@remix-run[\\/]router)[\\/]/,
162
+ priority: 0
163
+ }, config.optimization.splitChunks = {
164
+ ...currentConfig,
165
+ cacheGroups: {
166
+ ...extraGroups,
167
+ ...currentConfig.cacheGroups
168
+ }
169
+ }, config;
170
+ }, PLUGIN_NAME = 'unpack:react', pluginReact = (options = {})=>{
171
+ let { clickToComponent, reactCompiler } = options;
52
172
  return {
53
173
  name: PLUGIN_NAME,
54
174
  bundlerConfig: async (originalConfig, { unpackConfig, mergeConfig })=>{
55
- let config = originalConfig;
56
- const isRspack = 'rspack' === unpackConfig.bundler;
57
- const HtmlPlugin = isRspack ? core_namespaceObject.rspack.HtmlRspackPlugin : core_namespaceObject.HtmlWebpackPlugin;
58
- config = (0, external_mpa_cjs_namespaceObject.applyMpaConfig)({
175
+ let config = originalConfig, isRspack = 'rspack' === unpackConfig.bundler;
176
+ config = applyMpaConfig({
59
177
  config,
60
178
  unpackConfig,
61
179
  mergeConfig,
62
- HtmlPlugin
63
- });
64
- if ((0, core_namespaceObject.isDev)() && clickToComponent) config = await (0, index_cjs_namespaceObject.applyClickToComponentConfig)({
180
+ HtmlPlugin: isRspack ? core_namespaceObject.rspack.HtmlRspackPlugin : core_namespaceObject.HtmlWebpackPlugin
181
+ }), (0, core_namespaceObject.isDev)() && clickToComponent && (config = await applyClickToComponentConfig({
65
182
  config,
66
183
  unpackConfig
67
- });
68
- config = (0, external_splitChunks_cjs_namespaceObject.applySplitChunksConfig)({
184
+ })), config = applySplitChunksConfig({
69
185
  config,
70
186
  unpackConfig
71
- });
72
- if (reactCompiler && !(0, core_namespaceObject.getUserDepPath)(unpackConfig.root, 'react-compiler-runtime')) {
73
- core_namespaceObject.logger.error('dependency "react-compiler-runtime" not found, did you install it?');
74
- process.exit(1);
75
- }
76
- const jsExclude = [
187
+ }), reactCompiler && !(0, core_namespaceObject.getUserDepPath)(unpackConfig.root, 'react-compiler-runtime') && (core_namespaceObject.logger.error('dependency "react-compiler-runtime" not found, did you install it?'), process.exit(1));
188
+ let jsExclude = [
77
189
  /node_modules[\\/](?!\.unpack)/
78
- ];
79
- const swcLoader = isRspack ? 'builtin:swc-loader' : require.resolve('swc-loader');
80
- const ReactRefreshPlugin = isRspack ? plugin_react_refresh_default() : react_refresh_webpack_plugin_default();
81
- const getSwcOptions = ({ tsx })=>({
190
+ ], swcLoader = isRspack ? 'builtin:swc-loader' : require.resolve('swc-loader'), ReactRefreshPlugin = isRspack ? plugin_react_refresh_default() : react_refresh_webpack_plugin_default(), getSwcOptions = ({ tsx })=>({
82
191
  jsc: {
83
192
  parser: {
84
193
  tsx,
85
194
  syntax: "typescript",
86
- dynamicImport: true,
87
- decorators: true
195
+ dynamicImport: !0,
196
+ decorators: !0
88
197
  },
89
- externalHelpers: true,
198
+ externalHelpers: !0,
90
199
  transform: {
91
200
  react: {
92
201
  runtime: 'automatic',
@@ -108,7 +217,7 @@ const pluginReact = (options = {})=>{
108
217
  {
109
218
  loader: swcLoader,
110
219
  options: getSwcOptions({
111
- tsx: false
220
+ tsx: !1
112
221
  })
113
222
  }
114
223
  ]
@@ -120,22 +229,39 @@ const pluginReact = (options = {})=>{
120
229
  {
121
230
  loader: swcLoader,
122
231
  options: getSwcOptions({
123
- tsx: true
232
+ tsx: !0
124
233
  })
125
234
  },
126
235
  reactCompiler && {
127
- loader: external_node_path_default().resolve(__dirname, './react-compiler-loader/index.cjs'),
236
+ loader: external_node_path_default().resolve(__dirname, './reactCompilerLoader.mjs'),
128
237
  options: {
129
238
  target: (0, core_namespaceObject.getUserDepVersion)(unpackConfig.root, 'react').split('.')[0]
130
239
  }
131
240
  }
132
241
  ].filter(Boolean)
242
+ },
243
+ {
244
+ test: /\.svg$/i,
245
+ type: 'asset',
246
+ resourceQuery: /url/
247
+ },
248
+ {
249
+ test: /\.svg$/i,
250
+ issuer: /\.[jt]sx?$/,
251
+ resourceQuery: {
252
+ not: [
253
+ /url/
254
+ ]
255
+ },
256
+ use: [
257
+ require.resolve('@svgr/webpack')
258
+ ]
133
259
  }
134
260
  ]
135
261
  },
136
262
  plugins: [
137
263
  (0, core_namespaceObject.isDevServer)() && new ReactRefreshPlugin({
138
- overlay: false
264
+ overlay: !1
139
265
  })
140
266
  ].filter(Boolean),
141
267
  resolve: {
@@ -147,12 +273,10 @@ const pluginReact = (options = {})=>{
147
273
  }
148
274
  };
149
275
  };
150
- exports.PLUGIN_NAME = __webpack_exports__.PLUGIN_NAME;
151
- exports.pluginReact = __webpack_exports__.pluginReact;
152
- for(var __webpack_i__ in __webpack_exports__)if (-1 === [
276
+ for(var __webpack_i__ in exports.PLUGIN_NAME = __webpack_exports__.PLUGIN_NAME, exports.pluginReact = __webpack_exports__.pluginReact, __webpack_exports__)-1 === [
153
277
  "PLUGIN_NAME",
154
278
  "pluginReact"
155
- ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
279
+ ].indexOf(__webpack_i__) && (exports[__webpack_i__] = __webpack_exports__[__webpack_i__]);
156
280
  Object.defineProperty(exports, '__esModule', {
157
- value: true
281
+ value: !0
158
282
  });
package/dist/index.js CHANGED
@@ -1,65 +1,187 @@
1
1
  import __rslib_shim_module__ from 'module';
2
- const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(import.meta.url);
2
+ let require = __rslib_shim_module__.createRequire(import.meta.url);
3
3
  import { fileURLToPath as __webpack_fileURLToPath__ } from "node:url";
4
4
  import { dirname as __webpack_dirname__ } from "node:path";
5
- import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
6
- import * as __WEBPACK_EXTERNAL_MODULE__pmmmwh_react_refresh_webpack_plugin_143c1848__ from "@pmmmwh/react-refresh-webpack-plugin";
7
- import * as __WEBPACK_EXTERNAL_MODULE__rspack_plugin_react_refresh_db0cf031__ from "@rspack/plugin-react-refresh";
8
- import * as __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__ from "@unpackjs/core";
9
- import * as __WEBPACK_EXTERNAL_MODULE__click_to_component_index_js_1f068bff__ from "./click-to-component/index.js";
10
- import * as __WEBPACK_EXTERNAL_MODULE__mpa_js_c5cf22d9__ from "./mpa.js";
11
- import * as __WEBPACK_EXTERNAL_MODULE__splitChunks_js_b23140d8__ from "./splitChunks.js";
5
+ import node_path from "node:path";
6
+ import react_refresh_webpack_plugin from "@pmmmwh/react-refresh-webpack-plugin";
7
+ import plugin_react_refresh from "@rspack/plugin-react-refresh";
8
+ import { DEFAULT_BROWSERSLIST, HtmlWebpackPlugin, TEMPLATE_CONTENT, TEMP_DIR, colors, getPathInJs, getPort, getUserDepPath, getUserDepVersion, isDev, isDevServer, isFunction, isPlainObject, logger, removeDir, restartCleaners, rspack } from "@unpackjs/core";
9
+ import node_fs from "node:fs";
10
+ import node_http from "node:http";
11
+ import launch_editor from "launch-editor";
12
+ var click_to_component_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
13
+ let applyClickToComponentConfig = async ({ config, unpackConfig })=>{
14
+ let { port } = await new Promise((resolve)=>{
15
+ let server = node_http.createServer((req, res)=>{
16
+ let params = new URLSearchParams(req.url.slice(1)), file = decodeURIComponent(params.get('file')), line = Number(params.get('line')), column = Number(params.get('column'));
17
+ res.writeHead(200, {
18
+ 'Access-Control-Allow-Origin': '*',
19
+ 'Access-Control-Allow-Methods': '*',
20
+ 'Access-Control-Allow-Headers': '*',
21
+ 'Access-Control-Allow-Private-Network': 'true'
22
+ }), res.end('ok'), launch_editor(`${file}:${line}:${column}`);
23
+ });
24
+ getPort().then((port)=>{
25
+ server.listen(port, ()=>{
26
+ resolve({
27
+ port
28
+ });
29
+ });
30
+ }), restartCleaners.push(()=>new Promise((resolve)=>server.close(()=>resolve())));
31
+ }), injectScript = node_fs.readFileSync(node_path.resolve(click_to_component_dirname, './injectScript.js'), 'utf-8'), scriptTpl = `
32
+ if (!document.querySelector('#__click-to-component__')) {
33
+ const script = document.createElement('script')
34
+ window['CLICK_TO_COMPONENT'] = { port: ${port} }
35
+ script.setAttribute('type', 'text/javascript')
36
+ script.textContent = \`${injectScript}\`
37
+ document.body.appendChild(script)
38
+ }`;
39
+ if (unpackConfig.mpa) Object.values(config.entry).forEach((entryConfig)=>{
40
+ let filePath = entryConfig.import[0], content = node_fs.readFileSync(filePath, 'utf-8');
41
+ node_fs.writeFileSync(filePath, `${scriptTpl}\n${content}`, 'utf-8');
42
+ });
43
+ else {
44
+ let realEntryPath = node_path.resolve(config.context, TEMP_DIR, 'entries', `index.${port}.jsx`), tpl = `
45
+ ${scriptTpl}
46
+ import '${getPathInJs(node_path.resolve(Object.values(config.entry)[0]))}'
47
+ `, dir = node_path.dirname(realEntryPath);
48
+ node_fs.existsSync(dir) || node_fs.mkdirSync(dir, {
49
+ recursive: !0
50
+ }), node_fs.writeFileSync(realEntryPath, tpl, 'utf-8'), config.entry = {
51
+ main: realEntryPath
52
+ };
53
+ }
54
+ return config;
55
+ };
12
56
  var src_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
13
- const PLUGIN_NAME = 'unpack:react';
14
- const pluginReact = (options = {})=>{
15
- const { clickToComponent, reactCompiler } = options;
57
+ let PLUGIN_NAME = 'unpack:react', pluginReact = (options = {})=>{
58
+ let { clickToComponent, reactCompiler } = options;
16
59
  return {
17
60
  name: PLUGIN_NAME,
18
61
  bundlerConfig: async (originalConfig, { unpackConfig, mergeConfig })=>{
19
- let config = originalConfig;
20
- const isRspack = 'rspack' === unpackConfig.bundler;
21
- const HtmlPlugin = isRspack ? __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.rspack.HtmlRspackPlugin : __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.HtmlWebpackPlugin;
22
- config = (0, __WEBPACK_EXTERNAL_MODULE__mpa_js_c5cf22d9__.applyMpaConfig)({
62
+ let config = originalConfig, isRspack = 'rspack' === unpackConfig.bundler;
63
+ config = (({ config, unpackConfig, mergeConfig, HtmlPlugin })=>{
64
+ if (!unpackConfig.mpa) return config;
65
+ let isRspack = 'rspack' === unpackConfig.bundler, tempDirectory = node_path.join(TEMP_DIR, 'mpa'), userOptions = isPlainObject(unpackConfig.mpa) ? unpackConfig.mpa : {}, { entry, html } = (()=>{
66
+ let start = performance.now(), entry = {}, html = [], pagesRoot = node_path.join(unpackConfig.root, 'src', 'pages');
67
+ return node_fs.readdirSync(pagesRoot).forEach((filename)=>{
68
+ if (filename.startsWith('.')) return;
69
+ let indexFilePath = ((dir)=>{
70
+ for (let extension of [
71
+ '.tsx',
72
+ '.jsx'
73
+ ]){
74
+ let indexFilePath = node_path.join(dir, `index${extension}`);
75
+ if (node_fs.existsSync(indexFilePath)) return indexFilePath;
76
+ }
77
+ return null;
78
+ })(node_path.join(pagesRoot, filename));
79
+ if (indexFilePath) {
80
+ var _unpackConfig_html, _unpackConfig_html1, _unpackConfig_html2, _unpackConfig_html3, _unpackConfig_html4, _unpackConfig_html5, _unpackConfig_html6, _unpackConfig_html7, _unpackConfig_html8;
81
+ let pageConfig = ((indexPath)=>{
82
+ let filePath = node_path.join(indexPath, '../config.json'), pageConfig = {};
83
+ return node_fs.existsSync(filePath) && (pageConfig = JSON.parse(node_fs.readFileSync(filePath, 'utf-8'))), pageConfig;
84
+ })(indexFilePath), entryName = !0 === userOptions.lowerCase ? filename.toLowerCase() : filename;
85
+ pageConfig.filename && (entryName = pageConfig.filename.slice(0, -5)), entry[entryName] = {
86
+ import: [
87
+ indexFilePath
88
+ ]
89
+ }, pageConfig.template && (pageConfig.template = node_path.join(indexFilePath, '../', pageConfig.template)), html.push({
90
+ template: (null == (_unpackConfig_html = unpackConfig.html) ? void 0 : _unpackConfig_html.template) || (isRspack ? void 0 : ''),
91
+ templateContent: (null == (_unpackConfig_html1 = unpackConfig.html) ? void 0 : _unpackConfig_html1.templateContent) || ((null == (_unpackConfig_html2 = unpackConfig.html) ? void 0 : _unpackConfig_html2.template) ? !!isRspack && void 0 : TEMPLATE_CONTENT),
92
+ minify: !1,
93
+ filename: `${entryName}.html`,
94
+ chunks: [
95
+ entryName
96
+ ],
97
+ ...pageConfig,
98
+ templateParameters: {
99
+ mountId: null == (_unpackConfig_html3 = unpackConfig.html) ? void 0 : _unpackConfig_html3.mountId,
100
+ title: isFunction(null == (_unpackConfig_html4 = unpackConfig.html) ? void 0 : _unpackConfig_html4.title) ? null == (_unpackConfig_html5 = unpackConfig.html) ? void 0 : _unpackConfig_html5.title({
101
+ entryName
102
+ }) : (null == (_unpackConfig_html6 = unpackConfig.html) ? void 0 : _unpackConfig_html6.title) || '',
103
+ headTag: (null == (_unpackConfig_html7 = unpackConfig.html) ? void 0 : _unpackConfig_html7.headTag) || '',
104
+ ...null == (_unpackConfig_html8 = unpackConfig.html) ? void 0 : _unpackConfig_html8.templateParameters,
105
+ ...pageConfig.templateParameters
106
+ }
107
+ });
108
+ }
109
+ }), isDevServer() || logger.info(`collect entries in ${(performance.now() - start).toFixed(2)}ms ${colors.dim('[MPA]')}`), {
110
+ entry,
111
+ html
112
+ };
113
+ })();
114
+ return config = mergeConfig(config, {
115
+ entry: ((entry)=>{
116
+ var _userOptions_globalImport, _unpackConfig_html;
117
+ let root = unpackConfig.root;
118
+ removeDir(node_path.join(root, tempDirectory));
119
+ let globalImport = (null == (_userOptions_globalImport = userOptions.globalImport) ? void 0 : _userOptions_globalImport.reduce((acc, curr)=>`${acc}\nimport '${getPathInJs(node_path.resolve(root, curr))}'`, '')) || '', { layout } = userOptions, layoutImport = layout ? `import Layout from '${getPathInJs(node_path.resolve(root, layout))}'` : '', layoutJSX = layout ? '<Layout><App /></Layout>' : '<App />', rootElement = `document.getElementById('${null == (_unpackConfig_html = unpackConfig.html) ? void 0 : _unpackConfig_html.mountId}')`, renderer = `ReactDOM.createRoot(${rootElement}).render(${layoutJSX})`;
120
+ return Object.entries(entry).forEach(([entryName, entryConfig])=>{
121
+ let filePath = node_path.join(root, tempDirectory, `${entryName}.jsx`), tpl = `
122
+ import React from 'react'
123
+ import ReactDOM from 'react-dom/client'
124
+ import App from '${getPathInJs(entryConfig.import[0])}'${layoutImport && `\n${layoutImport}`}
125
+ ${globalImport}
126
+ ${renderer}
127
+ `, dir = node_path.dirname(filePath);
128
+ node_fs.existsSync(dir) || node_fs.mkdirSync(dir, {
129
+ recursive: !0
130
+ }), node_fs.writeFileSync(filePath, tpl, 'utf-8'), entryConfig.import[0] = filePath;
131
+ }), entry;
132
+ })(entry),
133
+ plugins: html.map((h)=>new HtmlPlugin(h))
134
+ });
135
+ })({
23
136
  config,
24
137
  unpackConfig,
25
138
  mergeConfig,
26
- HtmlPlugin
27
- });
28
- if ((0, __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.isDev)() && clickToComponent) config = await (0, __WEBPACK_EXTERNAL_MODULE__click_to_component_index_js_1f068bff__.applyClickToComponentConfig)({
139
+ HtmlPlugin: isRspack ? rspack.HtmlRspackPlugin : HtmlWebpackPlugin
140
+ }), isDev() && clickToComponent && (config = await applyClickToComponentConfig({
29
141
  config,
30
142
  unpackConfig
31
- });
32
- config = (0, __WEBPACK_EXTERNAL_MODULE__splitChunks_js_b23140d8__.applySplitChunksConfig)({
143
+ })), config = (({ config, unpackConfig })=>{
144
+ if ('split-by-experience' !== unpackConfig.performance.chunkSplit.strategy) return config;
145
+ let currentConfig = config.optimization.splitChunks, extraGroups = {};
146
+ return extraGroups.react = {
147
+ name: 'lib-react',
148
+ test: isDevServer() ? /node_modules[\\/](?:react|react-dom|scheduler|react-refresh|@rspack[\\/]plugin-react-refresh)[\\/]/ : /node_modules[\\/](?:react|react-dom|scheduler)[\\/]/,
149
+ priority: 0
150
+ }, extraGroups.router = {
151
+ name: 'lib-router',
152
+ test: /node_modules[\\/](?:react-router|react-router-dom|history|@remix-run[\\/]router)[\\/]/,
153
+ priority: 0
154
+ }, config.optimization.splitChunks = {
155
+ ...currentConfig,
156
+ cacheGroups: {
157
+ ...extraGroups,
158
+ ...currentConfig.cacheGroups
159
+ }
160
+ }, config;
161
+ })({
33
162
  config,
34
163
  unpackConfig
35
- });
36
- if (reactCompiler && !(0, __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.getUserDepPath)(unpackConfig.root, 'react-compiler-runtime')) {
37
- __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.logger.error('dependency "react-compiler-runtime" not found, did you install it?');
38
- process.exit(1);
39
- }
40
- const jsExclude = [
164
+ }), reactCompiler && !getUserDepPath(unpackConfig.root, 'react-compiler-runtime') && (logger.error('dependency "react-compiler-runtime" not found, did you install it?'), process.exit(1));
165
+ let jsExclude = [
41
166
  /node_modules[\\/](?!\.unpack)/
42
- ];
43
- const swcLoader = isRspack ? 'builtin:swc-loader' : require.resolve('swc-loader');
44
- const ReactRefreshPlugin = isRspack ? __WEBPACK_EXTERNAL_MODULE__rspack_plugin_react_refresh_db0cf031__["default"] : __WEBPACK_EXTERNAL_MODULE__pmmmwh_react_refresh_webpack_plugin_143c1848__["default"];
45
- const getSwcOptions = ({ tsx })=>({
167
+ ], swcLoader = isRspack ? 'builtin:swc-loader' : require.resolve('swc-loader'), getSwcOptions = ({ tsx })=>({
46
168
  jsc: {
47
169
  parser: {
48
170
  tsx,
49
171
  syntax: "typescript",
50
- dynamicImport: true,
51
- decorators: true
172
+ dynamicImport: !0,
173
+ decorators: !0
52
174
  },
53
- externalHelpers: true,
175
+ externalHelpers: !0,
54
176
  transform: {
55
177
  react: {
56
178
  runtime: 'automatic',
57
- refresh: (0, __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.isDevServer)()
179
+ refresh: isDevServer()
58
180
  }
59
181
  }
60
182
  },
61
183
  env: {
62
- targets: __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.DEFAULT_BROWSERSLIST
184
+ targets: DEFAULT_BROWSERSLIST
63
185
  }
64
186
  });
65
187
  return mergeConfig(config, {
@@ -72,7 +194,7 @@ const pluginReact = (options = {})=>{
72
194
  {
73
195
  loader: swcLoader,
74
196
  options: getSwcOptions({
75
- tsx: false
197
+ tsx: !1
76
198
  })
77
199
  }
78
200
  ]
@@ -84,27 +206,44 @@ const pluginReact = (options = {})=>{
84
206
  {
85
207
  loader: swcLoader,
86
208
  options: getSwcOptions({
87
- tsx: true
209
+ tsx: !0
88
210
  })
89
211
  },
90
212
  reactCompiler && {
91
- loader: __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].resolve(src_dirname, './react-compiler-loader/index.cjs'),
213
+ loader: node_path.resolve(src_dirname, './reactCompilerLoader.mjs'),
92
214
  options: {
93
- target: (0, __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.getUserDepVersion)(unpackConfig.root, 'react').split('.')[0]
215
+ target: getUserDepVersion(unpackConfig.root, 'react').split('.')[0]
94
216
  }
95
217
  }
96
218
  ].filter(Boolean)
219
+ },
220
+ {
221
+ test: /\.svg$/i,
222
+ type: 'asset',
223
+ resourceQuery: /url/
224
+ },
225
+ {
226
+ test: /\.svg$/i,
227
+ issuer: /\.[jt]sx?$/,
228
+ resourceQuery: {
229
+ not: [
230
+ /url/
231
+ ]
232
+ },
233
+ use: [
234
+ require.resolve('@svgr/webpack')
235
+ ]
97
236
  }
98
237
  ]
99
238
  },
100
239
  plugins: [
101
- (0, __WEBPACK_EXTERNAL_MODULE__unpackjs_core_a401ca19__.isDevServer)() && new ReactRefreshPlugin({
102
- overlay: false
240
+ isDevServer() && new (isRspack ? plugin_react_refresh : react_refresh_webpack_plugin)({
241
+ overlay: !1
103
242
  })
104
243
  ].filter(Boolean),
105
244
  resolve: {
106
245
  alias: {
107
- '@swc/helpers': __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__["default"].dirname(require.resolve('@swc/helpers/package.json'))
246
+ '@swc/helpers': node_path.dirname(require.resolve('@swc/helpers/package.json'))
108
247
  }
109
248
  }
110
249
  });