@unpackjs/core 4.1.0 → 4.2.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/compiled/css-loader/index.js +48 -39
- package/compiled/css-loader/package.json +1 -1
- package/compiled/less-loader/index.js +8 -8
- package/compiled/postcss-loader/index.js +8 -8
- package/compiled/sass-loader/index.js +8 -8
- package/dist/index.js +345 -108
- package/dist/transformLoader.js +12 -3
- package/dist-types/bundler-config/index.d.ts.map +1 -1
- package/dist-types/bundler-config/loaders/transformLoader.d.ts +1 -0
- package/dist-types/bundler-config/loaders/transformLoader.d.ts.map +1 -1
- package/dist-types/bundler-config/plugins/registerHooks.d.ts +1 -0
- package/dist-types/bundler-config/plugins/registerHooks.d.ts.map +1 -1
- package/dist-types/config.d.ts.map +1 -1
- package/dist-types/createUnpack.d.ts.map +1 -1
- package/dist-types/fs.d.ts +2 -0
- package/dist-types/fs.d.ts.map +1 -1
- package/dist-types/plugin.d.ts +8 -1
- package/dist-types/plugin.d.ts.map +1 -1
- package/dist-types/plugins/autoCssModules.d.ts.map +1 -1
- package/dist-types/plugins/svgIcons.d.ts +1 -1
- package/dist-types/plugins/svgIcons.d.ts.map +1 -1
- package/dist-types/plugins/unocss.d.ts +6 -0
- package/dist-types/plugins/unocss.d.ts.map +1 -0
- package/dist-types/types/config.d.ts +5 -0
- package/dist-types/types/config.d.ts.map +1 -1
- package/dist-types/types/plugin.d.ts +12 -1
- package/dist-types/types/plugin.d.ts.map +1 -1
- package/dist-types/utils.d.ts +1 -1
- package/dist-types/utils.d.ts.map +1 -1
- package/package.json +11 -6
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import node_path, { dirname as __rspack_dirname, join, sep } from "node:path";
|
|
|
6
6
|
import * as __rspack_external__compiled_launch_editor_index_js_29002383 from "../compiled/launch-editor/index.js";
|
|
7
7
|
import * as __rspack_external__compiled_webpack_merge_index_js_efd91626 from "../compiled/webpack-merge/index.js";
|
|
8
8
|
import { __webpack_require__ } from "./rslib-runtime.js";
|
|
9
|
-
import { rspack } from "@rspack/core";
|
|
9
|
+
import { Compilation, rspack } from "@rspack/core";
|
|
10
10
|
import cac from "cac";
|
|
11
11
|
import node_fs from "node:fs";
|
|
12
12
|
import node_readline from "node:readline";
|
|
@@ -17,6 +17,8 @@ import { format, promisify } from "node:util";
|
|
|
17
17
|
import { TraceMap, originalPositionFor } from "@jridgewell/trace-mapping";
|
|
18
18
|
import { parse } from "stacktrace-parser";
|
|
19
19
|
import node_zlib from "node:zlib";
|
|
20
|
+
import { createHash } from "node:crypto";
|
|
21
|
+
import magic_string from "magic-string";
|
|
20
22
|
import { expand } from "dotenv-expand";
|
|
21
23
|
import node_assert from "node:assert";
|
|
22
24
|
import { RspackDevServer } from "@rspack/dev-server";
|
|
@@ -124,7 +126,7 @@ let { merge: utils_mergeConfig } = __webpack_require__("compiled/webpack-merge")
|
|
|
124
126
|
process.env.NODE_ENV = env;
|
|
125
127
|
}, setDevServer = (isDevServer)=>{
|
|
126
128
|
process.env.DEV_SERVER = isDevServer ? 'true' : 'false';
|
|
127
|
-
}, isDev = ()=>'development' === getNodeEnv(), utils_isDevServer = ()=>'true' === process.env.DEV_SERVER,
|
|
129
|
+
}, isDev = ()=>'development' === getNodeEnv(), utils_isDevServer = ()=>'true' === process.env.DEV_SERVER, utils_isProd = ()=>'production' === getNodeEnv(), isWin = ()=>'win32' === process.platform, isString = (str)=>'string' == typeof str, isBoolean = (bool)=>'boolean' == typeof bool, isUndefined = (obj)=>void 0 === obj, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>null !== obj && 'object' == typeof obj, isPlainObject = (obj)=>isObject(obj) && '[object Object]' === Object.prototype.toString.call(obj), isRegExp = (obj)=>'[object RegExp]' === Object.prototype.toString.call(obj), prettyTime = (seconds)=>{
|
|
128
130
|
let toFixed = (num, len)=>{
|
|
129
131
|
let factor = 10 ** len;
|
|
130
132
|
return Math.floor(num * factor) / factor;
|
|
@@ -327,7 +329,25 @@ function getHtmlTemplateOrContent(rawTemplate, root) {
|
|
|
327
329
|
templateContent
|
|
328
330
|
};
|
|
329
331
|
}
|
|
330
|
-
let injectToHead = (html, script)=>html.replace(/<head(\s*[^>]*)>/i, (match)=>`${match}${script}`),
|
|
332
|
+
let injectToHead = (html, script)=>html.replace(/<head(\s*[^>]*)>/i, (match)=>`${match}${script}`), loadConfigFile = async (configFilePath)=>{
|
|
333
|
+
if (isNodeVersionAtLeast(22, 18) || /\.(?:js|mjs|cjs)$/.test(configFilePath)) {
|
|
334
|
+
logger_logger.debug('loading config file with native loader:', colors.dim(configFilePath));
|
|
335
|
+
let configFileURL = pathToFileURL(configFilePath).href, exportModule = await import(`${configFileURL}?t=${Date.now()}`);
|
|
336
|
+
return exportModule.default ? exportModule.default : exportModule;
|
|
337
|
+
}
|
|
338
|
+
logger_logger.debug('loading config file with jiti:', colors.dim(configFilePath));
|
|
339
|
+
let { createJiti } = await import("jiti"), jiti = createJiti(import.meta.url, {
|
|
340
|
+
moduleCache: !1,
|
|
341
|
+
interopDefault: !0,
|
|
342
|
+
nativeModules: [
|
|
343
|
+
'@rspack/core',
|
|
344
|
+
"typescript"
|
|
345
|
+
]
|
|
346
|
+
});
|
|
347
|
+
return await jiti.import(configFilePath, {
|
|
348
|
+
default: !0
|
|
349
|
+
});
|
|
350
|
+
}, logger_prefixes = {
|
|
331
351
|
wait: '○',
|
|
332
352
|
error: '⨯',
|
|
333
353
|
warn: '⚠',
|
|
@@ -368,36 +388,15 @@ let injectToHead = (html, script)=>html.replace(/<head(\s*[^>]*)>/i, (match)=>`$
|
|
|
368
388
|
})(type, message, ...args);
|
|
369
389
|
};
|
|
370
390
|
}), logger);
|
|
371
|
-
var config_filename = __rspack_fileURLToPath(import.meta.url);
|
|
372
391
|
async function loadConfig({ cliOptions, command }) {
|
|
373
392
|
'build' === command ? setNodeEnv(cliOptions?.watch ? 'development' : 'production') : (setNodeEnv('development'), setDevServer(!0));
|
|
374
393
|
let root = cliOptions?.root ? node_path.resolve(cliOptions.root) : process.cwd(), configFilePath = resolveConfigPath(root, cliOptions?.config), configExport = {};
|
|
375
|
-
if (configFilePath) {
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
logger_logger.debug('loading config file with jiti:', colors.dim(configFilePath));
|
|
382
|
-
let { createJiti } = await import("jiti"), jiti = createJiti(config_filename, {
|
|
383
|
-
moduleCache: !1,
|
|
384
|
-
interopDefault: !0,
|
|
385
|
-
nativeModules: [
|
|
386
|
-
'@rspack/core',
|
|
387
|
-
"typescript"
|
|
388
|
-
]
|
|
389
|
-
});
|
|
390
|
-
configExport = await jiti.import(configFilePath, {
|
|
391
|
-
default: !0
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
if ('function' == typeof configExport) {
|
|
395
|
-
let params = {
|
|
396
|
-
env: getNodeEnv(),
|
|
397
|
-
command: process.argv[2]
|
|
398
|
-
};
|
|
399
|
-
if (void 0 === (configExport = await configExport(params))) throw Error('unpack config function must return a config object.');
|
|
400
|
-
}
|
|
394
|
+
if (configFilePath && 'function' == typeof (configExport = await loadConfigFile(configFilePath))) {
|
|
395
|
+
let params = {
|
|
396
|
+
env: getNodeEnv(),
|
|
397
|
+
command: process.argv[2]
|
|
398
|
+
};
|
|
399
|
+
if (void 0 === (configExport = await configExport(params))) throw Error('unpack config function must return a config object.');
|
|
401
400
|
}
|
|
402
401
|
let applyOption = (path, value)=>{
|
|
403
402
|
void 0 !== value && set(configExport, path, value);
|
|
@@ -468,6 +467,18 @@ let removeDir = (dir)=>{
|
|
|
468
467
|
recursive: !0,
|
|
469
468
|
force: !0
|
|
470
469
|
});
|
|
470
|
+
}, emptyDir = (dir)=>{
|
|
471
|
+
if (!node_fs.existsSync(dir)) return void node_fs.mkdirSync(dir, {
|
|
472
|
+
recursive: !0
|
|
473
|
+
});
|
|
474
|
+
for (let file of node_fs.readdirSync(dir))node_fs.rmSync(node_path.join(dir, file), {
|
|
475
|
+
recursive: !0,
|
|
476
|
+
force: !0
|
|
477
|
+
});
|
|
478
|
+
}, ensureDir = (dir)=>{
|
|
479
|
+
node_fs.existsSync(dir) || node_fs.mkdirSync(dir, {
|
|
480
|
+
recursive: !0
|
|
481
|
+
});
|
|
471
482
|
}, restartCleaners = [], addRestartCleaner = (...cleaners)=>{
|
|
472
483
|
restartCleaners.push(...cleaners);
|
|
473
484
|
}, cleanUpBeforeRestart = async ()=>{
|
|
@@ -476,7 +487,7 @@ let removeDir = (dir)=>{
|
|
|
476
487
|
currentUnpackConfig = config;
|
|
477
488
|
}, unpackStartTime = 0, getUnpackStartTime = ()=>unpackStartTime, setUnpackStartTime = (time)=>{
|
|
478
489
|
unpackStartTime = time;
|
|
479
|
-
}, STYLE_IMPORT_RE = /import\s+([\s\S]
|
|
490
|
+
}, STYLE_IMPORT_RE = /import\s+((?:(?!\nimport\s)[\s\S])*?)\s+from\s+(['"])([^'"]+?\.(?:css|less|scss|sass)(?:\?[^'"]+)?(?:#[^'"]+)?)\2/g, TYPE_IMPORT_CLAUSE_RE = /^\s*type\b/, STYLE_EXT_HINTS = [
|
|
480
491
|
'.css',
|
|
481
492
|
'.less',
|
|
482
493
|
'.scss',
|
|
@@ -524,7 +535,7 @@ let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|
|
|
|
524
535
|
'react-router-dom': 'ReactRouterDOM'
|
|
525
536
|
};
|
|
526
537
|
return externalAlias[pkgName] ? externalAlias[pkgName] : pkgName.replace(/^@/, '').split(/[/\-.]/).filter(Boolean).map((part)=>part.charAt(0).toUpperCase() + part.slice(1)).join('');
|
|
527
|
-
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`,
|
|
538
|
+
}, getExternalValue = (pkgName)=>`window ${getExternalLibraryName(pkgName)}`, normalizeSvg = (content)=>content.replace(/<\?xml[\s\S]*?\?>/gi, '').replace(/<!DOCTYPE[\s\S]*?>/gi, '').replace(/<!--[\s\S]*?-->/g, '').trim(), extractSvgContent = (content)=>{
|
|
528
539
|
let match = content.match(/<svg\b([^>]*)>/i), viewBoxMatch = match?.[1]?.match(/viewBox\s*=\s*["']([^"']+)["']/i);
|
|
529
540
|
return {
|
|
530
541
|
inner: content.replace(/^[\s\S]*?<svg\b[^>]*>/i, '').replace(/<\/svg>[\s\S]*$/i, '').trim(),
|
|
@@ -544,10 +555,23 @@ let COMPRESSIBLE_REGEX = /\.(?:js|css|html|json|svg|txt|xml|xhtml|wasm|manifest|
|
|
|
544
555
|
if ('function' == typeof symbolId) return symbolId(name, filePath);
|
|
545
556
|
let id = (symbolId || 'icon-[dir]-[name]').replace(/\[name\]/g, name).replace(/\[dir\]/g, dir);
|
|
546
557
|
return id.replace(/--+/g, '-').replace(/^-+|-+$/g, '');
|
|
558
|
+
}, UNOCSS_CONFIG_FILES = [
|
|
559
|
+
'unocss.config.mjs',
|
|
560
|
+
'unocss.config.ts',
|
|
561
|
+
'unocss.config.js',
|
|
562
|
+
'unocss.config.mts',
|
|
563
|
+
'uno.config.mjs',
|
|
564
|
+
'uno.config.ts',
|
|
565
|
+
'uno.config.js',
|
|
566
|
+
'uno.config.mts'
|
|
567
|
+
], LAYER_MARK_ALL = '__ALL__', HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*\{\s*content\s*:\s*\\*"([^\\"]+)\\*";?\s*\}/g, LAYER_PLACEHOLDER_RE = /#--unocss--\s*\{\s*layer\s*:\s*(.+?)\s*(?:;\s*escape-view\s*:\s*(.+?)\s*)?;?\s*\}/g, SKIP_START_COMMENT = '@unocss-skip-start', SKIP_END_COMMENT = '@unocss-skip-end', SKIP_COMMENT_RE = RegExp(`(?://\\s*?${SKIP_START_COMMENT}\\s*?|/\\*\\s*?${SKIP_START_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_START_COMMENT}\\s*?-->)[\\s\\S]*?(?://\\s*?${SKIP_END_COMMENT}\\s*?|/\\*\\s*?${SKIP_END_COMMENT}\\s*?\\*/|<!--\\s*?${SKIP_END_COMMENT}\\s*?-->)`, 'g'), getCssEscaperForJsContent = (view)=>{
|
|
568
|
+
if (!view) return (css)=>css;
|
|
569
|
+
let prefix = {};
|
|
570
|
+
return view.trim().replace(/(\\*)\\(["'`\\])/g, (_, bs, char)=>(prefix[char] = bs.replace(/\\\\/g, '\\'), '')), (css)=>css.replace(/["'`\\]/g, (v)=>(prefix[v] || '') + v);
|
|
547
571
|
}, DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
|
|
548
572
|
function getNormalizedPluginsByHook(hook) {
|
|
549
573
|
let pluginMap = new Map();
|
|
550
|
-
|
|
574
|
+
(getCurrentUnpackConfig().plugins?.flat(1 / 0) || []).forEach((plugin)=>{
|
|
551
575
|
plugin && ((plugin, hook)=>{
|
|
552
576
|
if (!plugin[hook]) return !1;
|
|
553
577
|
let apply = plugin.apply;
|
|
@@ -558,12 +582,60 @@ function getNormalizedPluginsByHook(hook) {
|
|
|
558
582
|
};
|
|
559
583
|
return 'string' == typeof apply ? apply === env.command : !!apply(getCurrentUnpackConfig(), env);
|
|
560
584
|
})(plugin, hook) && pluginMap.set(plugin.name, plugin);
|
|
561
|
-
})
|
|
585
|
+
});
|
|
586
|
+
let normalizedPlugins = Array.from(pluginMap.values()), enforceOrder = (plugin)=>'pre' === plugin.enforce ? 0 : 'post' === plugin.enforce ? 2 : 1;
|
|
587
|
+
return normalizedPlugins.map((plugin, index)=>({
|
|
588
|
+
plugin,
|
|
589
|
+
index
|
|
590
|
+
})).sort((a, b)=>{
|
|
591
|
+
let diff = enforceOrder(a.plugin) - enforceOrder(b.plugin);
|
|
592
|
+
return 0 !== diff ? diff : a.index - b.index;
|
|
593
|
+
}).map((item)=>item.plugin);
|
|
562
594
|
}
|
|
595
|
+
let createPluginHookTimer = (plugin, hook)=>{
|
|
596
|
+
let startTime = 0;
|
|
597
|
+
return {
|
|
598
|
+
start: ()=>{
|
|
599
|
+
startTime = performance.now();
|
|
600
|
+
},
|
|
601
|
+
end: ()=>{
|
|
602
|
+
let duration = performance.now() - startTime;
|
|
603
|
+
logger_logger.debug(`${colors.magenta('[plugin]')} ${colors.cyan(plugin.name)} ${colors.blue(hook)} ${colors.dim('in')} ${colors.yellow(`${duration.toFixed(2)}ms`)}`);
|
|
604
|
+
}
|
|
605
|
+
};
|
|
606
|
+
}, TRANSFORM_TIMING_STORE = Symbol.for('unpack:transformTimingMap'), globalScope = globalThis, transformTimingMap = globalScope[TRANSFORM_TIMING_STORE] ?? new WeakMap();
|
|
563
607
|
async function applyPluginsByHook(hook, runner) {
|
|
608
|
+
let shouldMeasure = 'processAssets' !== hook && 'transform' !== hook;
|
|
609
|
+
for (let plugin of getNormalizedPluginsByHook(hook)){
|
|
610
|
+
let impl = plugin[hook];
|
|
611
|
+
if (!shouldMeasure) {
|
|
612
|
+
await runner(impl, plugin);
|
|
613
|
+
continue;
|
|
614
|
+
}
|
|
615
|
+
let timer = createPluginHookTimer(plugin, hook);
|
|
616
|
+
timer.start();
|
|
617
|
+
try {
|
|
618
|
+
await runner(impl, plugin);
|
|
619
|
+
} finally{
|
|
620
|
+
timer.end();
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
function applyPluginsByHookSync(hook, runner) {
|
|
625
|
+
let shouldMeasure = 'processAssets' !== hook && 'transform' !== hook;
|
|
564
626
|
for (let plugin of getNormalizedPluginsByHook(hook)){
|
|
565
627
|
let impl = plugin[hook];
|
|
566
|
-
|
|
628
|
+
if (!shouldMeasure) {
|
|
629
|
+
runner(impl, plugin);
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
let timer = createPluginHookTimer(plugin, hook);
|
|
633
|
+
timer.start();
|
|
634
|
+
try {
|
|
635
|
+
runner(impl, plugin);
|
|
636
|
+
} finally{
|
|
637
|
+
timer.end();
|
|
638
|
+
}
|
|
567
639
|
}
|
|
568
640
|
}
|
|
569
641
|
async function applyBuildAnalyzeConfig({ config, unpackConfig }) {
|
|
@@ -622,6 +694,7 @@ async function applyCacheConfig({ config, unpackConfig, envFilePaths }) {
|
|
|
622
694
|
}
|
|
623
695
|
});
|
|
624
696
|
}
|
|
697
|
+
globalScope[TRANSFORM_TIMING_STORE] = transformTimingMap;
|
|
625
698
|
let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\/])?([^\\/]+)/, SPLIT_STRATEGY_DISPATCHER = {
|
|
626
699
|
'split-by-module': function(ctx) {
|
|
627
700
|
let { forceSplittingGroups, defaultConfig } = ctx;
|
|
@@ -750,7 +823,7 @@ class JsMinifyPlugin {
|
|
|
750
823
|
apply(compiler) {
|
|
751
824
|
let meta = JSON.stringify({
|
|
752
825
|
name: jsMinify_PLUGIN_NAME,
|
|
753
|
-
version: "4.1
|
|
826
|
+
version: "4.2.1",
|
|
754
827
|
options: this.minifyOptions
|
|
755
828
|
});
|
|
756
829
|
compiler.hooks.compilation.tap(jsMinify_PLUGIN_NAME, (compilation)=>{
|
|
@@ -853,15 +926,15 @@ async function compileDone(compiler, stats) {
|
|
|
853
926
|
if (!fileInfo) return;
|
|
854
927
|
if (fileInfo === lastFileInfo ? sameCount++ : (lastFileInfo = fileInfo, sameCount = 1), isDebug()) {
|
|
855
928
|
var modules;
|
|
856
|
-
let nodeModulesStats, nodeModulesPath;
|
|
857
|
-
Object.entries((modules = stats.compilation.modules, nodeModulesStats = {}, nodeModulesPath = node_path.resolve(root, 'node_modules'), modules.forEach((module)=>{
|
|
929
|
+
let nodeModulesStats, nodeModulesPath, sortedStats;
|
|
930
|
+
(sortedStats = Object.entries((modules = stats.compilation.modules, nodeModulesStats = {}, nodeModulesPath = node_path.resolve(root, 'node_modules'), modules.forEach((module)=>{
|
|
858
931
|
let { resource } = module;
|
|
859
932
|
if (resource?.includes(nodeModulesPath)) {
|
|
860
933
|
let packageName, pathParts = node_path.relative(nodeModulesPath, resource).split(sep);
|
|
861
934
|
(packageName = '.pnpm' === pathParts[0] && pathParts.length >= 4 ? pathParts[3].startsWith('@') ? `${pathParts[3]}/${pathParts[4]}` : pathParts[3] : pathParts[0].startsWith('@') ? `${pathParts[0]}/${pathParts[1]}` : pathParts[0]) && (nodeModulesStats[packageName] = (nodeModulesStats[packageName] || 0) + 1);
|
|
862
935
|
}
|
|
863
|
-
}), nodeModulesStats)).sort((a, b)=>a[1] - b[1]).forEach(([packageName, count])=>{
|
|
864
|
-
|
|
936
|
+
}), nodeModulesStats)).sort((a, b)=>a[1] - b[1])).forEach(([packageName, count], i)=>{
|
|
937
|
+
i >= sortedStats.length - 10 && logger_logger.debug(`[dependency] ${colors.cyan(packageName)}: ${colors.yellow(count)} modules`);
|
|
865
938
|
});
|
|
866
939
|
}
|
|
867
940
|
isDebug() || logger_logger.clear(), console.log(colors.dim(getTime()), colors.cyan(`[${getCurrentUnpackConfig()._context.callerName}]`), colors.brand(utils_isDevServer() ? 'hmr update' : 'build'), `${colors.dim(fileInfo)}${sameCount > 1 ? ` ${colors.yellow(`(x${sameCount})`)}` : ''}`, isDebug() ? colors.dim(`| ${prettyTime(getCompileTime(stats))} (${stats.compilation.modules.size} modules)`) : '');
|
|
@@ -894,28 +967,69 @@ class ProgressPlugin extends rspack.ProgressPlugin {
|
|
|
894
967
|
let registerHooks_PLUGIN_NAME = 'RegisterHooksPlugin';
|
|
895
968
|
class RegisterHooksPlugin {
|
|
896
969
|
isFirstCompile = !0;
|
|
970
|
+
lastVirtualModules = new Map();
|
|
897
971
|
apply(compiler) {
|
|
898
|
-
|
|
972
|
+
let virtualModulesPlugin = new rspack.experiments.VirtualModulesPlugin();
|
|
973
|
+
virtualModulesPlugin.apply(compiler), compiler.hooks.beforeCompile.tapPromise(registerHooks_PLUGIN_NAME, async ()=>{
|
|
899
974
|
await applyPluginsByHook('buildStart', async (impl)=>{
|
|
900
975
|
await impl({
|
|
901
976
|
compiler,
|
|
902
977
|
isFirstCompile: this.isFirstCompile,
|
|
903
|
-
isWatch:
|
|
978
|
+
isWatch: isDev()
|
|
904
979
|
});
|
|
905
980
|
});
|
|
906
981
|
}), compiler.hooks.done.tapPromise(registerHooks_PLUGIN_NAME, async (stats)=>{
|
|
907
|
-
|
|
982
|
+
stats?.compilation && ((compilation)=>{
|
|
983
|
+
let pluginMap = transformTimingMap.get(compilation);
|
|
984
|
+
if (pluginMap) {
|
|
985
|
+
for (let [pluginName, total] of pluginMap)logger_logger.debug(`${colors.magenta('[plugin]')} ${colors.cyan(pluginName)} ${colors.blue('transform')} ${colors.dim('in')} ${colors.yellow(`${total.toFixed(2)}ms`)}`);
|
|
986
|
+
transformTimingMap.delete(compilation);
|
|
987
|
+
}
|
|
988
|
+
})(stats.compilation), await applyPluginsByHook('buildEnd', async (impl)=>{
|
|
908
989
|
await impl({
|
|
909
990
|
compiler,
|
|
910
991
|
isFirstCompile: this.isFirstCompile,
|
|
911
|
-
isWatch:
|
|
992
|
+
isWatch: isDev(),
|
|
912
993
|
stats
|
|
913
994
|
});
|
|
914
995
|
}), this.isFirstCompile = !1;
|
|
996
|
+
});
|
|
997
|
+
let updateVirtualModules = ()=>{
|
|
998
|
+
applyPluginsByHookSync('virtualModules', (impl)=>{
|
|
999
|
+
Object.entries(impl()).forEach(([path, content])=>{
|
|
1000
|
+
this.lastVirtualModules.get(path) !== content && (this.lastVirtualModules.set(path, content), virtualModulesPlugin.writeModule(path, content));
|
|
1001
|
+
});
|
|
1002
|
+
});
|
|
1003
|
+
};
|
|
1004
|
+
compiler.hooks.afterDone.tap(registerHooks_PLUGIN_NAME, ()=>{
|
|
1005
|
+
isDev() && setTimeout(()=>{
|
|
1006
|
+
updateVirtualModules();
|
|
1007
|
+
}, 100);
|
|
915
1008
|
}), compiler.hooks.compilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
|
|
916
1009
|
rspack.HtmlRspackPlugin.getCompilationHooks(compilation).beforeEmit.tapPromise(registerHooks_PLUGIN_NAME, async (data)=>(await applyPluginsByHook('transformHtml', async (impl)=>{
|
|
917
1010
|
data.html = await impl(data.html);
|
|
918
1011
|
}), data));
|
|
1012
|
+
}), compiler.hooks.thisCompilation.tap(registerHooks_PLUGIN_NAME, (compilation)=>{
|
|
1013
|
+
updateVirtualModules(), applyPluginsByHook('processAssets', (impl, plugin)=>{
|
|
1014
|
+
let { stage, handler } = impl;
|
|
1015
|
+
compilation.hooks.processAssets.tapPromise({
|
|
1016
|
+
name: registerHooks_PLUGIN_NAME,
|
|
1017
|
+
stage
|
|
1018
|
+
}, async (assets)=>{
|
|
1019
|
+
let timer = createPluginHookTimer(plugin, 'processAssets');
|
|
1020
|
+
timer.start();
|
|
1021
|
+
try {
|
|
1022
|
+
await handler({
|
|
1023
|
+
assets,
|
|
1024
|
+
compilation,
|
|
1025
|
+
sources: rspack.sources,
|
|
1026
|
+
compiler
|
|
1027
|
+
});
|
|
1028
|
+
} finally{
|
|
1029
|
+
timer.end();
|
|
1030
|
+
}
|
|
1031
|
+
});
|
|
1032
|
+
});
|
|
919
1033
|
});
|
|
920
1034
|
}
|
|
921
1035
|
}
|
|
@@ -964,7 +1078,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
964
1078
|
bundlerConfig
|
|
965
1079
|
};
|
|
966
1080
|
setCurrentUnpackConfig(unpackConfig), await applyPluginsByHook('configResolved', async (impl)=>{
|
|
967
|
-
await impl(unpackConfig);
|
|
1081
|
+
await impl(unpackConfig, originalUnpackConfig._context);
|
|
968
1082
|
});
|
|
969
1083
|
let tsconfigPath = node_path.resolve(unpackConfig.root, 'tsconfig.json'), isTs = node_fs.existsSync(tsconfigPath), minifyOptions = isPlainObject(unpackConfig.build?.minify) ? unpackConfig.build?.minify : {}, { publicVars, filePaths: envFilePaths } = function({ cwd = process.cwd(), mode = getNodeEnv(), prefixes = [
|
|
970
1084
|
'PUBLIC_'
|
|
@@ -976,14 +1090,14 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
976
1090
|
`.env.${mode}`,
|
|
977
1091
|
`.env.${mode}.local`
|
|
978
1092
|
].map((filename)=>join(cwd, filename)).filter(isFileSync), parsed = {};
|
|
979
|
-
for (let envPath of filePaths)Object.assign(parsed, function(src) {
|
|
1093
|
+
for (let envPath of filePaths)logger_logger.debug('loading env file:', colors.dim(envPath)), Object.assign(parsed, function(src) {
|
|
980
1094
|
let match, obj = {}, lines = src.toString();
|
|
981
1095
|
for(lines = lines.replace(/\r\n?/gm, '\n'); null != (match = DOTENV_LINE.exec(lines));){
|
|
982
1096
|
let key = match[1], value = match[2] || '', maybeQuote = (value = value.trim())[0];
|
|
983
1097
|
value = value.replace(/^(['"`])([\s\S]*)\1$/gm, '$2'), '"' === maybeQuote && (value = (value = value.replace(/\\n/g, '\n')).replace(/\\r/g, '\r')), obj[key] = value;
|
|
984
1098
|
}
|
|
985
1099
|
return obj;
|
|
986
|
-
}(node_fs.readFileSync(envPath)))
|
|
1100
|
+
}(node_fs.readFileSync(envPath)));
|
|
987
1101
|
parsed.NODE_ENV && (processEnv.NODE_ENV = parsed.NODE_ENV), expand({
|
|
988
1102
|
parsed,
|
|
989
1103
|
processEnv
|
|
@@ -1141,9 +1255,9 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1141
1255
|
hints: !1
|
|
1142
1256
|
}
|
|
1143
1257
|
};
|
|
1144
|
-
|
|
1145
|
-
let { filter, handler } =
|
|
1146
|
-
config.module.rules.
|
|
1258
|
+
return applyPluginsByHookSync('transform', (impl, plugin)=>{
|
|
1259
|
+
let { filter, handler } = impl;
|
|
1260
|
+
config.module.rules.unshift({
|
|
1147
1261
|
exclude: NODE_MODULES_REGEX,
|
|
1148
1262
|
...filter,
|
|
1149
1263
|
enforce: 'pre',
|
|
@@ -1151,13 +1265,13 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1151
1265
|
{
|
|
1152
1266
|
loader: node_path.resolve(bundler_config_dirname, './transformLoader.js'),
|
|
1153
1267
|
options: {
|
|
1154
|
-
handler
|
|
1268
|
+
handler,
|
|
1269
|
+
pluginName: plugin.name
|
|
1155
1270
|
}
|
|
1156
1271
|
}
|
|
1157
1272
|
]
|
|
1158
1273
|
});
|
|
1159
|
-
}
|
|
1160
|
-
return config = (({ config, unpackConfig })=>{
|
|
1274
|
+
}), config = (({ config, unpackConfig })=>{
|
|
1161
1275
|
let { chunkSplit } = unpackConfig.performance || {};
|
|
1162
1276
|
if (chunkSplit?.strategy) {
|
|
1163
1277
|
let forceSplittingGroups = {};
|
|
@@ -1461,7 +1575,7 @@ async function getBundlerConfig(originalUnpackConfig) {
|
|
|
1461
1575
|
unpackConfig
|
|
1462
1576
|
})), await applyPluginsByHook('bundlerConfig', async (impl)=>{
|
|
1463
1577
|
config = await impl(config, {
|
|
1464
|
-
...
|
|
1578
|
+
...originalUnpackConfig._context,
|
|
1465
1579
|
unpackConfig,
|
|
1466
1580
|
mergeConfig: utils_mergeConfig
|
|
1467
1581
|
});
|
|
@@ -1478,9 +1592,9 @@ async function unpackBuild(unpackConfig) {
|
|
|
1478
1592
|
stats?.hasErrors() && console.log(stats.toString({
|
|
1479
1593
|
colors: !0,
|
|
1480
1594
|
preset: 'errors-only'
|
|
1481
|
-
})),
|
|
1595
|
+
})), utils_isProd() && compiler.close(()=>{});
|
|
1482
1596
|
};
|
|
1483
|
-
|
|
1597
|
+
utils_isProd() ? compiler.run(handler) : compiler.watch({}, handler);
|
|
1484
1598
|
}
|
|
1485
1599
|
var openBrowser_dirname = __rspack_dirname(__rspack_fileURLToPath(import.meta.url));
|
|
1486
1600
|
async function openBrowser(url) {
|
|
@@ -1588,7 +1702,7 @@ async function unpackDev(unpackConfig) {
|
|
|
1588
1702
|
...middlewares
|
|
1589
1703
|
]);
|
|
1590
1704
|
let server = new RspackDevServer(devServerOptions, compiler);
|
|
1591
|
-
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.1
|
|
1705
|
+
await server.start(), logger_logger.greet(` ${colors.brand(`${colors.bold(unpackConfig._context.callerName.toUpperCase())} v4.2.1`)} ${colors.dim('ready in')} ${colors.bold(Math.ceil(performance.now() - getUnpackStartTime()))} ${colors.dim('ms')}\n`), printServerUrls({
|
|
1592
1706
|
port,
|
|
1593
1707
|
host: unpackConfig.server.host,
|
|
1594
1708
|
base: unpackConfig.base
|
|
@@ -1602,11 +1716,10 @@ async function unpackDev(unpackConfig) {
|
|
|
1602
1716
|
function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'unpack' }) {
|
|
1603
1717
|
let _context = {
|
|
1604
1718
|
callerName,
|
|
1605
|
-
version: "4.1
|
|
1719
|
+
version: "4.2.1",
|
|
1606
1720
|
cachePath: 'node_modules/.unpack'
|
|
1607
1721
|
}, resolveConfig = (mode)=>{
|
|
1608
|
-
|
|
1609
|
-
let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root, rootPath1, inject, domId, registerCode, namesCode, virtualModules, ensureVirtualModules, mergedConfig = utils_mergeConfig({
|
|
1722
|
+
let rootPath, outputPath, basePath, cachedTraceMap, fs, isValidMethodName, parseFrame, formatOriginalLocation, formatFullStack, resolveErrorLocationAndStack, shouldTransformDeepImport, preJsAssets, jsAssets, cssAssets, bundledDepsCachePath, deepImportPkgPattern, deepImportRegex, plugin, root, uno, configFilePath, configOrPathFromUnpackConfig, defaultsFromUnpackConfig, compilerRef, rootDir, unoConfig, tokens, unocssCacheDir, tokensCachePath, timeCachePath, layersCachePath, bundlerCacheDir, cachedTokensLength, cachedLayersLength, tasks, requestedLayers, layerImportRE, ensureReady, invalidate, flushTasks, getVirtualModuleContent, hash, restoreSkipCode, applyUnoTransformers, getResolvedLayers, optionsFromUnpackConfig, rootPath1, registerCode, namesCode, defaultConfig = {
|
|
1610
1723
|
root: cwd,
|
|
1611
1724
|
base: '/',
|
|
1612
1725
|
sourceMap: 'production' !== mode && 'cheap-module-source-map',
|
|
@@ -1643,7 +1756,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
1643
1756
|
name: 'unpack:auto-css-modules',
|
|
1644
1757
|
transform: {
|
|
1645
1758
|
filter: {
|
|
1646
|
-
test:
|
|
1759
|
+
test: /\.(?:[jt]sx|vue)$/
|
|
1647
1760
|
},
|
|
1648
1761
|
handler: (code)=>STYLE_EXT_HINTS.some((ext)=>code.includes(ext)) ? code.replace(STYLE_IMPORT_RE, (full, importClause, quote, spec)=>TYPE_IMPORT_CLAUSE_RE.test(importClause) || spec.includes('?') || spec.includes('#') ? full : `import ${importClause} from ${quote}${spec}?module${quote}`) : null
|
|
1649
1762
|
}
|
|
@@ -2328,52 +2441,176 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
2328
2441
|
let log = colors.blue('Total'.padEnd(longest + 2));
|
|
2329
2442
|
log += colors.blue(displaySize(totalSize)), console.log(log += colors.dim(` │ gzip: ${displaySize(totalCompressedSize)}`));
|
|
2330
2443
|
}
|
|
2331
|
-
})
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2444
|
+
}),
|
|
2445
|
+
(rootDir = process.cwd(), unoConfig = {}, tokens = new Set(), unocssCacheDir = '', tokensCachePath = '', timeCachePath = '', layersCachePath = '', bundlerCacheDir = '', cachedTokensLength = 0, cachedLayersLength = 0, tasks = [], requestedLayers = new Set([
|
|
2446
|
+
LAYER_MARK_ALL
|
|
2447
|
+
]), layerImportRE = /(['"])uno:([^'"]+?)\.css\1/g, ensureReady = async ()=>{
|
|
2448
|
+
var root, configOrPath;
|
|
2449
|
+
let core = await import("@unocss/core"), resolvedConfigOrPath = (root = rootDir, 'string' != typeof (configOrPath = (void 0) ?? configOrPathFromUnpackConfig) || node_path.isAbsolute(configOrPath) ? configOrPath : node_path.resolve(root, configOrPath)), resolvedDefaults = (void 0) ?? defaultsFromUnpackConfig, configFromOption = {};
|
|
2450
|
+
if (isPlainObject(resolvedConfigOrPath) ? configFromOption = resolvedConfigOrPath : isString(resolvedConfigOrPath) && (configFilePath = resolvedConfigOrPath), configFilePath || (configFilePath = ((root, customConfig)=>{
|
|
2451
|
+
for (let file of UNOCSS_CONFIG_FILES){
|
|
2452
|
+
let configFile = node_path.join(root, file);
|
|
2453
|
+
if (node_fs.existsSync(configFile)) return configFile;
|
|
2454
|
+
}
|
|
2455
|
+
})(rootDir)), configFilePath && node_fs.existsSync(configFilePath) && (configFromOption = utils_mergeConfig(configFromOption, await loadConfigFile(configFilePath))), resolvedDefaults && (configFromOption = utils_mergeConfig(resolvedDefaults, configFromOption)), unoConfig = configFromOption, uno = await core.createGenerator(unoConfig), tokens = new Set(), node_fs.existsSync(tokensCachePath)) {
|
|
2456
|
+
let cached = JSON.parse(node_fs.readFileSync(tokensCachePath, 'utf-8'));
|
|
2457
|
+
Array.isArray(cached) && (cachedTokensLength = (tokens = new Set(cached)).size, logger_logger.debug(colors.yellow(`[unocss] Load ${tokens.size} token from cache.`)));
|
|
2458
|
+
}
|
|
2459
|
+
if (node_fs.existsSync(layersCachePath)) {
|
|
2460
|
+
let cached = JSON.parse(node_fs.readFileSync(layersCachePath, 'utf-8'));
|
|
2461
|
+
Array.isArray(cached) && (cachedLayersLength = (requestedLayers = new Set(cached)).size, logger_logger.debug(colors.yellow(`[unocss] Load ${requestedLayers.size} layer from cache.`)));
|
|
2462
|
+
}
|
|
2463
|
+
}, invalidate = ()=>{
|
|
2464
|
+
setTimeout(()=>{
|
|
2465
|
+
compilerRef.watching.invalidate(), logger_logger.debug(colors.yellow('[unocss] Invalidation triggered.'));
|
|
2466
|
+
}, 0);
|
|
2467
|
+
}, flushTasks = async ()=>{
|
|
2468
|
+
if (!tasks.length) return;
|
|
2469
|
+
let pending = tasks.map((t)=>t());
|
|
2470
|
+
tasks = [], await Promise.all(pending);
|
|
2471
|
+
}, getVirtualModuleContent = (layer)=>{
|
|
2472
|
+
let code, layersKey = Array.from(requestedLayers).sort().join(','), hash = (code = `${tokens.size}|${layer}|${layersKey}`, createHash('sha256').update(code).digest('hex').slice(0, 8));
|
|
2473
|
+
return `#--unocss-hash--{content:"${hash}"}#--unocss--{layer:${layer};escape-view:\\"\\'\\\`\\\\}`;
|
|
2474
|
+
}, hash = (str)=>{
|
|
2475
|
+
let i, l, hVal = 0x811c9dc5;
|
|
2476
|
+
for(i = 0, l = str.length; i < l; i++)hVal ^= str.charCodeAt(i), hVal += (hVal << 1) + (hVal << 4) + (hVal << 7) + (hVal << 8) + (hVal << 24);
|
|
2477
|
+
return `00000${(hVal >>> 0).toString(36)}`.slice(-6);
|
|
2478
|
+
}, restoreSkipCode = (code, map)=>{
|
|
2479
|
+
let next = code;
|
|
2480
|
+
for (let [withHashKey, matched] of map.entries())next = next.replaceAll(withHashKey, matched);
|
|
2481
|
+
return next;
|
|
2482
|
+
}, applyUnoTransformers = async (original, id, enforce = 'default')=>{
|
|
2483
|
+
if (original.includes('@unocss-ignore')) return null;
|
|
2484
|
+
let transformers = (uno.config.transformers || []).filter((i)=>(i.enforce || 'default') === enforce);
|
|
2485
|
+
if (!transformers.length) return null;
|
|
2486
|
+
let skipMap = new Map(), code = original, s = new magic_string(((code, map, rules, keyFlag)=>{
|
|
2487
|
+
let next = code;
|
|
2488
|
+
for (let item of Array.from(next.matchAll(rules)))if (null != item) {
|
|
2489
|
+
let matched = item[0], withHashKey = `${keyFlag}${hash(matched)}`;
|
|
2490
|
+
map.set(withHashKey, matched), next = next.replace(matched, withHashKey);
|
|
2491
|
+
}
|
|
2492
|
+
return next;
|
|
2493
|
+
})(code, skipMap, SKIP_COMMENT_RE, '@unocss-skip-placeholder-'));
|
|
2494
|
+
for (let t of transformers)(!t.idFilter || t.idFilter(id)) && (await t.transform(s, id, {
|
|
2495
|
+
uno,
|
|
2496
|
+
tokens,
|
|
2497
|
+
invalidate
|
|
2498
|
+
}), s.hasChanged() && (s = new magic_string(code = restoreSkipCode(s.toString(), skipMap))));
|
|
2499
|
+
return code !== original ? code : null;
|
|
2500
|
+
}, getResolvedLayers = ()=>Array.from(requestedLayers).filter((layer)=>layer !== LAYER_MARK_ALL), {
|
|
2501
|
+
name: 'unpack:unocss',
|
|
2502
|
+
apply: (config)=>!!config.unocss,
|
|
2503
|
+
configResolved: async (config, { cachePath })=>{
|
|
2504
|
+
if (rootDir = config.root, unocssCacheDir = node_path.resolve(rootDir, cachePath, 'unocss'), tokensCachePath = node_path.resolve(unocssCacheDir, 'tokens'), timeCachePath = node_path.resolve(unocssCacheDir, 'created_at'), layersCachePath = node_path.resolve(unocssCacheDir, 'layers'), bundlerCacheDir = node_path.resolve(rootDir, cachePath, 'cache'), ensureDir(unocssCacheDir), (()=>{
|
|
2505
|
+
let now = Date.now(), last = 0;
|
|
2506
|
+
if (!node_fs.existsSync(timeCachePath)) {
|
|
2507
|
+
node_fs.writeFileSync(timeCachePath, String(now), 'utf-8'), emptyDir(bundlerCacheDir);
|
|
2508
|
+
return;
|
|
2365
2509
|
}
|
|
2510
|
+
let parsed = Number(node_fs.readFileSync(timeCachePath, 'utf-8').trim());
|
|
2511
|
+
Number.isNaN(parsed) || (last = parsed), now - last < 604800000 || (emptyDir(unocssCacheDir), emptyDir(bundlerCacheDir), node_fs.writeFileSync(timeCachePath, String(now), 'utf-8'));
|
|
2512
|
+
})(), Array.isArray(config.unocss)) {
|
|
2513
|
+
let [configOrPathValue, defaultsValue] = config.unocss;
|
|
2514
|
+
configOrPathFromUnpackConfig = configOrPathValue, defaultsFromUnpackConfig = defaultsValue;
|
|
2366
2515
|
}
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2516
|
+
await ensureReady();
|
|
2517
|
+
},
|
|
2518
|
+
bundlerConfig: (config, { mergeConfig, unpackConfig })=>mergeConfig(config, {
|
|
2519
|
+
experiments: {
|
|
2520
|
+
cache: {
|
|
2521
|
+
type: unpackConfig.performance?.cache ? 'persistent' : 'memory',
|
|
2522
|
+
buildDependencies: configFilePath ? [
|
|
2523
|
+
configFilePath
|
|
2524
|
+
] : void 0
|
|
2525
|
+
}
|
|
2526
|
+
}
|
|
2527
|
+
}),
|
|
2528
|
+
buildStart ({ compiler }) {
|
|
2529
|
+
compilerRef = compiler;
|
|
2530
|
+
},
|
|
2531
|
+
buildEnd () {
|
|
2532
|
+
tokens.size !== cachedTokensLength && (node_fs.writeFileSync(tokensCachePath, JSON.stringify(Array.from(tokens)), 'utf-8'), logger_logger.debug(colors.yellow(`[unocss] Add ${tokens.size - cachedTokensLength} token to cache.`)), cachedTokensLength = tokens.size), requestedLayers.size !== cachedLayersLength && (node_fs.writeFileSync(layersCachePath, JSON.stringify(Array.from(requestedLayers)), 'utf-8'), logger_logger.debug(colors.yellow(`[unocss] Add ${requestedLayers.size - cachedLayersLength} layer to cache.`)), cachedLayersLength = requestedLayers.size);
|
|
2533
|
+
},
|
|
2534
|
+
transform: {
|
|
2535
|
+
filter: {
|
|
2536
|
+
test: /\.(vue|svelte|[jt]sx?|vine\.ts|mdx?|astro|elm|php|phtml|marko)($|\?)/
|
|
2537
|
+
},
|
|
2538
|
+
handler: async (code, id)=>{
|
|
2539
|
+
var task;
|
|
2540
|
+
if (code.includes('uno:')) for (let match of code.matchAll(layerImportRE)){
|
|
2541
|
+
let layer = match[2];
|
|
2542
|
+
layer && requestedLayers.add(layer);
|
|
2543
|
+
}
|
|
2544
|
+
if (JS_REGEX.test(id) && !code.includes('@unocss-include')) return null;
|
|
2545
|
+
let transformedCode = code, preTransformed = await applyUnoTransformers(transformedCode, id, 'pre');
|
|
2546
|
+
null != preTransformed && (transformedCode = preTransformed);
|
|
2547
|
+
let defaultTransformed = await applyUnoTransformers(transformedCode, id, 'default');
|
|
2548
|
+
null != defaultTransformed && (transformedCode = defaultTransformed);
|
|
2549
|
+
let postTransformed = await applyUnoTransformers(transformedCode, id, 'post');
|
|
2550
|
+
return null != postTransformed && (transformedCode = postTransformed), task = async ()=>{
|
|
2551
|
+
await uno.applyExtractors(transformedCode.replace(SKIP_COMMENT_RE, ''), id, tokens);
|
|
2552
|
+
}, tasks.push(task), transformedCode === code ? null : transformedCode;
|
|
2553
|
+
}
|
|
2554
|
+
},
|
|
2555
|
+
processAssets: {
|
|
2556
|
+
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
|
|
2557
|
+
handler: async ({ compilation, sources })=>{
|
|
2558
|
+
await flushTasks();
|
|
2559
|
+
let resolvedLayers = getResolvedLayers(), result = await uno.generate(tokens, {
|
|
2560
|
+
minify: !0
|
|
2561
|
+
});
|
|
2562
|
+
for (let file of Object.keys(compilation.assets)){
|
|
2563
|
+
if ('*' === file || file.includes('vendor')) continue;
|
|
2564
|
+
let code = compilation.assets[file].source().toString();
|
|
2565
|
+
if (!code.includes('#--unocss')) continue;
|
|
2566
|
+
let isJsAsset = /\.(?:[cm]?js|[cm]?jsx)$/.test(file), replaced = !1;
|
|
2567
|
+
code = (code = code.replace(HASH_PLACEHOLDER_RE, '')).replace(LAYER_PLACEHOLDER_RE, (_, layer, escapeView)=>{
|
|
2568
|
+
replaced = !0;
|
|
2569
|
+
let css = layer.trim() === LAYER_MARK_ALL ? result.getLayers(void 0, resolvedLayers) : result.getLayer(layer) || '';
|
|
2570
|
+
return isJsAsset ? getCssEscaperForJsContent(escapeView)(css) : css;
|
|
2571
|
+
}), replaced && compilation.updateAsset(file, new sources.RawSource(code));
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
},
|
|
2575
|
+
virtualModules: ()=>({
|
|
2576
|
+
'uno.css': getVirtualModuleContent(LAYER_MARK_ALL),
|
|
2577
|
+
...getResolvedLayers().reduce((acc, layer)=>(acc[`uno:${layer}.css`] = getVirtualModuleContent(layer), acc), {})
|
|
2578
|
+
})
|
|
2579
|
+
}),
|
|
2580
|
+
(rootPath1 = '', registerCode = '', namesCode = '', {
|
|
2581
|
+
name: 'unpack:svg-icons',
|
|
2582
|
+
apply: (config)=>!!config.svgIcons,
|
|
2583
|
+
configResolved: (config)=>{
|
|
2584
|
+
rootPath1 = config.root || process.cwd(), optionsFromUnpackConfig = config.svgIcons, (()=>{
|
|
2585
|
+
let root, resolvedOptions = (void 0) ?? optionsFromUnpackConfig, inject = resolvedOptions.inject || 'body-last', domId = resolvedOptions.customDomId || '__svg__icons__dom__', { svg, names } = ((iconDirs, symbolId, customDomId)=>{
|
|
2586
|
+
let symbols = [], names = [], idSet = new Set();
|
|
2587
|
+
for (let dir of iconDirs)for (let file of readSvgFiles(dir)){
|
|
2588
|
+
let { inner, viewBox } = extractSvgContent(normalizeSvg(node_fs.readFileSync(file, 'utf-8'))), id = toSymbolId(file, dir, symbolId);
|
|
2589
|
+
!id || idSet.has(id) || (idSet.add(id), names.push(id), symbols.push(`<symbol id="${id}"${viewBox ? ` viewBox="${viewBox}"` : ''}>${inner}</symbol>`));
|
|
2590
|
+
}
|
|
2591
|
+
return {
|
|
2592
|
+
svg: `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="${customDomId}" style="position: absolute; width: 0; height: 0" aria-hidden="true">${symbols.join('')}</svg>`,
|
|
2593
|
+
names
|
|
2594
|
+
};
|
|
2595
|
+
})((root = rootPath1, (resolvedOptions.iconDirs || []).map((dir)=>node_path.isAbsolute(dir) ? dir : node_path.resolve(root, dir))), resolvedOptions.symbolId, domId);
|
|
2596
|
+
registerCode = `const svgDomId = ${JSON.stringify(domId)}\nconst svgHtml = ${JSON.stringify(svg)}\nconst inject = (position) => {\n if (typeof document === 'undefined') return\n if (document.getElementById(svgDomId)) return\n const div = document.createElement('div')\n div.innerHTML = svgHtml\n const svgEl = div.firstElementChild\n if (!svgEl) return\n if (position === 'head' && document.head) {\n document.head.prepend(svgEl)\n return\n }\n const body = document.body\n if (!body) return\n if (position === 'body-first' && body.firstChild) {\n body.insertBefore(svgEl, body.firstChild)\n } else {\n body.appendChild(svgEl)\n }\n}\nconst mount = () => inject(${JSON.stringify(inject)})\nif (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', mount)\n } else {\n mount()\n }\n}\nexport default mount`, namesCode = `export const svgIconNames = ${JSON.stringify(names)}\nexport default svgIconNames`;
|
|
2597
|
+
})();
|
|
2598
|
+
},
|
|
2599
|
+
virtualModules: ()=>({
|
|
2600
|
+
'~svg-icons-register': registerCode || 'export default null',
|
|
2601
|
+
'~svg-icons-names': namesCode || 'export default []'
|
|
2602
|
+
}),
|
|
2603
|
+
transform: {
|
|
2604
|
+
filter: {
|
|
2605
|
+
test: JS_REGEX
|
|
2606
|
+
},
|
|
2607
|
+
handler: (code)=>code.includes('virtual:svg-icons-') ? code.replace('virtual:svg-icons-', '~svg-icons-') : null
|
|
2608
|
+
}
|
|
2609
|
+
})
|
|
2610
|
+
]
|
|
2611
|
+
};
|
|
2612
|
+
return {
|
|
2613
|
+
...utils_mergeConfig(defaultConfig, userConfig),
|
|
2377
2614
|
_context
|
|
2378
2615
|
};
|
|
2379
2616
|
};
|
|
@@ -2382,7 +2619,7 @@ function createUnpack({ cwd = process.cwd(), config: userConfig, callerName = 'u
|
|
|
2382
2619
|
let mode = watch ? 'development' : 'production';
|
|
2383
2620
|
setNodeEnv(mode);
|
|
2384
2621
|
let config = resolveConfig(mode);
|
|
2385
|
-
console.log(colors.brand(`${callerName} v4.1
|
|
2622
|
+
console.log(colors.brand(`${callerName} v4.2.1`), colors.cyan(`building for ${mode}...`)), await unpackBuild(config);
|
|
2386
2623
|
},
|
|
2387
2624
|
dev: async ()=>{
|
|
2388
2625
|
setUnpackStartTime(performance.now());
|
|
@@ -2531,7 +2768,7 @@ function runCLI() {
|
|
|
2531
2768
|
logger_logger.clear(), logger_logger.info(`${node_path.basename(file)} changed, restarting server...`), await watcher.close(), await cleanUpBeforeRestart(), startServer(options);
|
|
2532
2769
|
});
|
|
2533
2770
|
});
|
|
2534
|
-
devCommand.option('-o, --open [url]', 'Open browser on startup').option('--port <port>', 'Specify port').option('--host', 'Expose hostname').action(startServer), cli.help(), cli.version("4.1
|
|
2771
|
+
devCommand.option('-o, --open [url]', 'Open browser on startup').option('--port <port>', 'Specify port').option('--host', 'Expose hostname').action(startServer), cli.help(), cli.version("4.2.1"), cli.parse();
|
|
2535
2772
|
}
|
|
2536
2773
|
var src_CSS_MODULES_NAMED_EXPORT = !1;
|
|
2537
|
-
export { ALL_INTERFACES_IPV4, CSS_MODULES_EXPORTS_CONVENTION, CSS_MODULES_LOCAL_IDENT_NAME, DEV_DEFAULT_FILENAME, JSX_REGEX, JS_REGEX, LOCALHOST, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, SCRIPT_REGEX, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, debounce, defineConfig, esVersionToBrowserslist, external_tinyglobby_glob as glob, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, globSync, injectToHead, isBoolean, isDebug, isDev, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isRegExp, isString, isUndefined,
|
|
2774
|
+
export { ALL_INTERFACES_IPV4, CSS_MODULES_EXPORTS_CONVENTION, CSS_MODULES_LOCAL_IDENT_NAME, DEV_DEFAULT_FILENAME, JSX_REGEX, JS_REGEX, LOCALHOST, NODE_MODULES_REGEX, PROD_DEFAULT_FILENAME, SCRIPT_REGEX, TEMPLATE_CONTENT, addRestartCleaner, cleanUpBeforeRestart, clearLine, colors, convertBasicAnsiColors, createChokidar, createUnpack, debounce, defineConfig, emptyDir, ensureDir, esVersionToBrowserslist, external_tinyglobby_glob as glob, findExists, getAddressUrls, getCompiledPkgPath, getCurrentUnpackConfig, getHtmlTemplateOrContent, getIpv4Interfaces, getNodeEnv, getOrSetDefault, getPathInJs, getPort, getTime, getUnpackStartTime, getUserDepPath, getUserDepVersion, globSync, injectToHead, isBoolean, isDebug, isDev, isEmptyDir, isFileExists, isFileSync, isFunction, isNodeVersionAtLeast, isObject, isPlainObject, isRegExp, isString, isUndefined, isWin, launchEditor, loadConfig, loadConfigFile, logUpdate, logger_LogColor as LogColor, logger_logger as logger, normalizePublicPath, openBrowser, pLimit, pathExists, pathToExportIdentifier, prettyTime, printServerUrls, removeDir, resolveConfigPath, rspack, runCLI, set, setCurrentUnpackConfig, setDevServer, setNodeEnv, setUnpackStartTime, src_CSS_MODULES_NAMED_EXPORT as CSS_MODULES_NAMED_EXPORT, trackPerformance, utils_isDevServer as isDevServer, utils_isProd as isProd, utils_mergeConfig as mergeConfig };
|