@flatjs/evolve 2.1.0-next.4 → 2.1.0-next.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (116) hide show
  1. package/dist/constants.js +26 -1
  2. package/dist/create-webpack/create-externals.js +6 -1
  3. package/dist/create-webpack/create-optimization.js +41 -1
  4. package/dist/create-webpack/create-output.js +35 -1
  5. package/dist/create-webpack/create-performance.js +7 -1
  6. package/dist/create-webpack/create-plugins.js +77 -1
  7. package/dist/create-webpack/create-resolve.js +37 -1
  8. package/dist/create-webpack/create-rule-sets.js +19 -1
  9. package/dist/create-webpack/load-webpack-config.js +56 -1
  10. package/dist/create-webpack/resolve-public-path.js +15 -1
  11. package/dist/create-webpack/rule-sets/constants.js +3 -1
  12. package/dist/create-webpack/rule-sets/rule-assets.js +50 -1
  13. package/dist/create-webpack/rule-sets/rule-css.js +101 -1
  14. package/dist/create-webpack/rule-sets/rule-less.js +44 -1
  15. package/dist/create-webpack/rule-sets/rule-scripts.js +34 -1
  16. package/dist/create-webpack/rule-sets/rule-svg-icon.js +25 -1
  17. package/dist/create-webpack/rule-sets/rule-utils.js +10 -1
  18. package/dist/create-webpack/types.js +1 -1
  19. package/dist/default-options.js +84 -1
  20. package/dist/define-config/define-config.js +4 -1
  21. package/dist/define-config/index.js +1 -1
  22. package/dist/dev-server/add-compiler-to-dev-server.js +58 -1
  23. package/dist/dev-server/create-app-page-route.js +13 -1
  24. package/dist/dev-server/create-dev-server-compiler-tasks.js +52 -1
  25. package/dist/dev-server/create-dev-server-entries.js +27 -1
  26. package/dist/dev-server/create-dev-server.js +24 -1
  27. package/dist/dev-server/index.js +6 -1
  28. package/dist/dev-server/middlewares/create-page-middleware.js +33 -1
  29. package/dist/dev-server/middlewares/create-public-assets-middleware.js +25 -1
  30. package/dist/dev-server/middlewares/get-all-sorted-modules.js +24 -1
  31. package/dist/dev-server/middlewares/get-bundle-asset.js +7 -1
  32. package/dist/dev-server/middlewares/get-dev-server-host-uri.js +5 -1
  33. package/dist/dev-server/middlewares/get-hmr-runtime-chunks.js +14 -1
  34. package/dist/dev-server/middlewares/get-normalized-entry-name.js +14 -1
  35. package/dist/dev-server/middlewares/get-page-main-html.js +42 -1
  36. package/dist/dev-server/middlewares/get-page-module-html.js +120 -1
  37. package/dist/dev-server/middlewares/get-project-virtual-path.js +3 -1
  38. package/dist/dev-server/middlewares/get-runtime-manifest.js +25 -1
  39. package/dist/dev-server/middlewares/index.js +2 -1
  40. package/dist/dev-server/middlewares/types.js +1 -1
  41. package/dist/errors/evolve-build-error.js +10 -1
  42. package/dist/helpers/allow-px2rem-for-module.js +6 -1
  43. package/dist/helpers/assert-only-single-entry-item.js +23 -1
  44. package/dist/helpers/chunk-entry-map.js +21 -1
  45. package/dist/helpers/enable-bundle-hashname-for-module.js +6 -1
  46. package/dist/helpers/filter-actived-entries.js +42 -1
  47. package/dist/helpers/get-bundle-file-name.js +23 -1
  48. package/dist/helpers/get-git-root.js +4 -1
  49. package/dist/helpers/get-html-plugin-config.js +47 -1
  50. package/dist/helpers/get-max-process-tasks.js +7 -1
  51. package/dist/helpers/get-pacakge-dir.js +13 -1
  52. package/dist/helpers/index.js +17 -1
  53. package/dist/helpers/json-serializer.js +52 -1
  54. package/dist/helpers/merge-babel-options.js +45 -1
  55. package/dist/helpers/normalize-entry-map.js +38 -1
  56. package/dist/helpers/normalize-page-proxy.js +9 -1
  57. package/dist/helpers/normalize-resolve-alias.js +7 -1
  58. package/dist/helpers/open-page.js +15 -1
  59. package/dist/helpers/print-log.js +49 -1
  60. package/dist/helpers/refresh-evolve-mock-options.js +34 -1
  61. package/dist/helpers/resolve-entry-map-input-files.js +20 -1
  62. package/dist/helpers/script-injects.js +39 -1
  63. package/dist/helpers/should-enable-react-fast-refresh.js +10 -1
  64. package/dist/helpers/split-to-multi-compiler.js +32 -1
  65. package/dist/index.js +5 -1
  66. package/dist/load-config/index.js +1 -1
  67. package/dist/load-config/load-evolve-config.js +41 -1
  68. package/dist/load-config/types.js +1 -1
  69. package/dist/main/create-thread-worker.js +42 -1
  70. package/dist/main/env-verify.js +21 -1
  71. package/dist/main/get-worker-path.js +5 -1
  72. package/dist/main/index.js +4 -1
  73. package/dist/main/prepare-build.js +38 -1
  74. package/dist/main/prepare-serve.js +45 -1
  75. package/dist/main/prepare-static.js +30 -1
  76. package/dist/main/start-build-dynamic.js +157 -1
  77. package/dist/main/start-build-worker.js +46 -1
  78. package/dist/main/start-build.js +53 -1
  79. package/dist/main/start-one-entry-build.js +35 -1
  80. package/dist/main/start-serve.js +34 -1
  81. package/dist/main/start-static.js +19 -1
  82. package/dist/minimizer/create-minimizers.js +25 -1
  83. package/dist/minimizer/default-options.js +14 -1
  84. package/dist/minimizer/image-minimizer.js +65 -1
  85. package/dist/minimizer/index.js +1 -1
  86. package/dist/minimizer/terser-minimizer.js +15 -3
  87. package/dist/minimizer/types.js +1 -1
  88. package/dist/plugins/circular-dependency/circular-dependency-plugin.js +119 -1
  89. package/dist/plugins/circular-dependency/index.js +15 -1
  90. package/dist/plugins/clean-webpack/clean-webpack-plugin.js +173 -1
  91. package/dist/plugins/clean-webpack/index.js +22 -1
  92. package/dist/plugins/define-variable/define-variable-plugin.js +28 -1
  93. package/dist/plugins/define-variable/index.js +1 -1
  94. package/dist/plugins/html-inject-scripts/plugin-html-inject-script.js +27 -1
  95. package/dist/plugins/module-federation/external-template-remotes.js +92 -1
  96. package/dist/plugins/module-federation/index.js +1 -1
  97. package/dist/plugins/module-federation/module-federation.js +98 -1
  98. package/dist/plugins/multi-html/index.js +15 -1
  99. package/dist/plugins/multi-html/multi-html-cdn-plugin.js +84 -1
  100. package/dist/plugins/multi-html/multi-html-plugin.js +70 -1
  101. package/dist/plugins/ts-checker/index.d.ts +1 -0
  102. package/dist/plugins/ts-checker/index.js +1 -0
  103. package/dist/plugins/ts-checker/ts-checker-plugin.d.ts +4 -0
  104. package/dist/plugins/ts-checker/ts-checker-plugin.js +18 -0
  105. package/dist/types/index.js +8 -1
  106. package/dist/types/types-ci.js +1 -1
  107. package/dist/types/types-dev-server.js +1 -1
  108. package/dist/types/types-entry-map.js +1 -1
  109. package/dist/types/types-federation.js +1 -1
  110. package/dist/types/types-loader-options.js +1 -1
  111. package/dist/types/types-modular-import.js +1 -1
  112. package/dist/types/types-multi-html.js +1 -1
  113. package/dist/types/types-options.js +1 -1
  114. package/dist/types/types-plugin-options.js +1 -1
  115. package/dist/types/types-webpack.js +1 -1
  116. package/package.json +2 -2
package/dist/constants.js CHANGED
@@ -1 +1,26 @@
1
- export const moduleName="@flatjs/evolve";export const configFileName="flatjs-evolve";export const viewportScripts='(function(d){var j;var b=1;var i=1;var h=750;var c=100;function e(s,o){var q=d.document;var l=q.documentElement;var k=navigator.userAgent;var m=k.toLowerCase().indexOf("android")>-1;i=d.devicePixelRatio||1;if(i>3){i=3}if(m){i=1}console.log("current devicePixelRatio:",i);l.setAttribute("data-dpr",i.toString());var p=q.querySelector(\'meta[name="viewport"]\');if(!p){b=1/i;p=q.createElement("meta");p.setAttribute("name","viewport");q.head.appendChild(p);p.setAttribute(["content","width=device-width,user-scalable=no,initial-scale=",b,",maximum-scale=",b,",minimum-scale=",b].join(""))}function n(){var t=document.documentElement.clientWidth;j=t/o*(s/i)*i;q.documentElement.style.fontSize=String(j)+"px"}var r;d.addEventListener("resize",function(){clearTimeout(r);r=setTimeout(n,300)},false);d.addEventListener("onload",n,false);n()}e(c,h);window.fabricViewport={currRem:j,currDpr:i,currScale:b,dpiPX2px:function f(k){return parseFloat(k.toString())/j*100+"px"},px2DPIpx:function a(k){return parseFloat(k.toString())/100*j+"px"},px2rem:function g(k){return parseFloat(k.toString())/100+"rem"}}})(window);';export const polyfill=["https://polyfill.io/v3/polyfill.min.js?features=Array.from%2CArray.isArray%2CArray.of%2CArray.prototype.entries%2CArray.prototype.every%2CArray.prototype.fill%2CArray.prototype.filter%2CArray.prototype.find%2CArray.prototype.findIndex%2CArray.prototype.flat%2CArray.prototype.forEach%2CArray.prototype.flatMap%2CArray.prototype.keys%2CArray.prototype.indexOf%2CArray.prototype.includes%2CArray.prototype.lastIndexOf%2CArray.prototype.map%2CArray.prototype.reduce%2CArray.prototype.reduceRight%2CArray.prototype.some%2CArray.prototype.sort%2CArray.prototype.values%2CArrayBuffer%2CBlob%2CDataView%2CDate.now%2CObject.assign%2CObject.create%2CObject.defineProperties%2CObject.defineProperty%2CObject.entries%2CObject.freeze%2CObject.fromEntries%2CObject.getOwnPropertySymbols%2CObject.getOwnPropertyNames%2CObject.getOwnPropertyDescriptors%2CObject.getOwnPropertyDescriptor%2CObject.getPrototypeOf%2CObject.is%2CObject.isExtensible%2CObject.isFrozen%2CObject.isSealed%2CObject.keys%2CObject.values%2CObject.setPrototypeOf%2CPromise%2CPromise.prototype.finally%2CReflect%2CReflect.apply%2CReflect.construct%2CReflect.defineProperty%2CReflect.deleteProperty%2CReflect.getPrototypeOf%2CReflect.getOwnPropertyDescriptor%2CReflect.get%2CReflect.ownKeys%2CReflect.isExtensible%2CReflect.has%2CReflect.preventExtensions%2CReflect.set%2CReflect.setPrototypeOf%2CSet%2CString.prototype.trimStart%2CString.prototype.trimEnd%2CString.prototype.trim%2CString.prototype.startsWith%2CString.prototype.repeat%2CString.prototype.replaceAll%2CString.prototype.padStart%2CString.prototype.padEnd%2CMap%2CObject.seal%2Cconsole.groupEnd%2Cconsole.group"];export const devReactFastRefresh={runtime:"reactRefreshRuntime",reactRefreshSetup:"reactRefreshSetup"};
1
+ export const moduleName = `@flatjs/evolve`;
2
+ /**
3
+ * the configuration file of `flat-evolve`
4
+ * flatjs-evolve.config.ts,.mjs,.mts
5
+ */
6
+ export const configFileName = `flatjs-evolve`;
7
+ /**
8
+ * `viewport.js`, Used to support the mobile `rem` adaptive solution.
9
+ * The viewport code is dynamically inserted to `html` file via `html-plugin`
10
+ */
11
+ export const viewportScripts = `(function(d){var j;var b=1;var i=1;var h=750;var c=100;function e(s,o){var q=d.document;var l=q.documentElement;var k=navigator.userAgent;var m=k.toLowerCase().indexOf("android")>-1;i=d.devicePixelRatio||1;if(i>3){i=3}if(m){i=1}console.log("current devicePixelRatio:",i);l.setAttribute("data-dpr",i.toString());var p=q.querySelector('meta[name="viewport"]');if(!p){b=1/i;p=q.createElement("meta");p.setAttribute("name","viewport");q.head.appendChild(p);p.setAttribute(["content","width=device-width,user-scalable=no,initial-scale=",b,",maximum-scale=",b,",minimum-scale=",b].join(""))}function n(){var t=document.documentElement.clientWidth;j=t/o*(s/i)*i;q.documentElement.style.fontSize=String(j)+"px"}var r;d.addEventListener("resize",function(){clearTimeout(r);r=setTimeout(n,300)},false);d.addEventListener("onload",n,false);n()}e(c,h);window.fabricViewport={currRem:j,currDpr:i,currScale:b,dpiPX2px:function f(k){return parseFloat(k.toString())/j*100+"px"},px2DPIpx:function a(k){return parseFloat(k.toString())/100*j+"px"},px2rem:function g(k){return parseFloat(k.toString())/100+"rem"}}})(window);`;
12
+ /**
13
+ * https://polyfill.io
14
+ */
15
+ export const polyfill = [
16
+ `https://polyfill.io/v3/polyfill.min.js?features=Array.from%2CArray.isArray%2CArray.of%2CArray.prototype.entries%2CArray.prototype.every%2CArray.prototype.fill%2CArray.prototype.filter%2CArray.prototype.find%2CArray.prototype.findIndex%2CArray.prototype.flat%2CArray.prototype.forEach%2CArray.prototype.flatMap%2CArray.prototype.keys%2CArray.prototype.indexOf%2CArray.prototype.includes%2CArray.prototype.lastIndexOf%2CArray.prototype.map%2CArray.prototype.reduce%2CArray.prototype.reduceRight%2CArray.prototype.some%2CArray.prototype.sort%2CArray.prototype.values%2CArrayBuffer%2CBlob%2CDataView%2CDate.now%2CObject.assign%2CObject.create%2CObject.defineProperties%2CObject.defineProperty%2CObject.entries%2CObject.freeze%2CObject.fromEntries%2CObject.getOwnPropertySymbols%2CObject.getOwnPropertyNames%2CObject.getOwnPropertyDescriptors%2CObject.getOwnPropertyDescriptor%2CObject.getPrototypeOf%2CObject.is%2CObject.isExtensible%2CObject.isFrozen%2CObject.isSealed%2CObject.keys%2CObject.values%2CObject.setPrototypeOf%2CPromise%2CPromise.prototype.finally%2CReflect%2CReflect.apply%2CReflect.construct%2CReflect.defineProperty%2CReflect.deleteProperty%2CReflect.getPrototypeOf%2CReflect.getOwnPropertyDescriptor%2CReflect.get%2CReflect.ownKeys%2CReflect.isExtensible%2CReflect.has%2CReflect.preventExtensions%2CReflect.set%2CReflect.setPrototypeOf%2CSet%2CString.prototype.trimStart%2CString.prototype.trimEnd%2CString.prototype.trim%2CString.prototype.startsWith%2CString.prototype.repeat%2CString.prototype.replaceAll%2CString.prototype.padStart%2CString.prototype.padEnd%2CMap%2CObject.seal%2Cconsole.groupEnd%2Cconsole.group`,
17
+ ];
18
+ /**
19
+ * Applies the react-refresh Babel plugin on non-production modes only
20
+ * Ensure `react-refresh/runtime` is hoisted and shared
21
+ * https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/docs/TROUBLESHOOTING.md#externalising-react
22
+ */
23
+ export const devReactFastRefresh = {
24
+ runtime: `reactRefreshRuntime`,
25
+ reactRefreshSetup: `reactRefreshSetup`,
26
+ };
@@ -1 +1,6 @@
1
- import{mergeOptions}from"@flatjs/common";export const createExternals=(t={},e)=>{const o=e[1],r=o.options?.externals||{};return mergeOptions(t,r)};
1
+ import { mergeOptions } from '@flatjs/common';
2
+ export const createExternals = (externals = {}, entryItem) => {
3
+ const entryItemContent = entryItem[1];
4
+ const entryItemExternals = entryItemContent.options?.externals || {};
5
+ return mergeOptions(externals, entryItemExternals);
6
+ };
@@ -1 +1,41 @@
1
- import{join}from"node:path";import{devReactFastRefresh}from"../constants.js";import{shouldEnableReactFastRefresh}from"../helpers/should-enable-react-fast-refresh.js";import{createMinimizers}from"../minimizer/index.js";export const createOptimization=(e,i,n)=>({nodeEnv:e?"development":"production",chunkIds:"named",moduleIds:"named",runtimeChunk:!!shouldEnableReactFastRefresh(e,n,i)&&{name:()=>join(n[0],devReactFastRefresh.runtime)},minimize:!1!==i.webpack?.minimizer&&!e,minimizer:createMinimizers(e,i.webpack),splitChunks:{name:!1,chunks:"all",minSize:25e5,cacheGroups:{default:!1,defaultVendors:!1}}});
1
+ import { join } from 'node:path';
2
+ import { devReactFastRefresh } from '../constants.js';
3
+ import { shouldEnableReactFastRefresh } from '../helpers/should-enable-react-fast-refresh.js';
4
+ import { createMinimizers } from '../minimizer/index.js';
5
+ export const createOptimization = (serveMode, evolveOptions, entryItem) => {
6
+ // Indicates current we use `hot` mode for `webpack-dev-server` hot reload true.
7
+ const enabledHmr = shouldEnableReactFastRefresh(serveMode, entryItem, evolveOptions);
8
+ const webpackOptimization = {
9
+ nodeEnv: serveMode ? 'development' : 'production',
10
+ chunkIds: 'named',
11
+ moduleIds: 'named',
12
+ // Ensure `react-refresh/runtime` is hoisted and shared, Could be replicated via a vendors chunk
13
+ // NOTE: This is only for `HMR` mode, if we have no `HMR` mode, we should not use this! it always be `false`
14
+ runtimeChunk: enabledHmr
15
+ ? {
16
+ name: () => join(entryItem[0], devReactFastRefresh.runtime),
17
+ }
18
+ : false,
19
+ // This is true in production mode. Tell webpack to minimize the bundle using the TerserPlugin
20
+ minimize: evolveOptions.webpack?.minimizer !== false && !serveMode,
21
+ // Note: the `minimizer` will executed must be wait until `minimize` is `true`
22
+ minimizer: createMinimizers(serveMode, evolveOptions.webpack),
23
+ // Disabled WARNING in webpack while chunk exceed the recommended size limit for `serve`
24
+ splitChunks: {
25
+ // It is recommended to set splitChunks.name to false for production builds
26
+ // so that it doesn't change names unnecessarily.
27
+ name: false,
28
+ // include all types of chunks
29
+ // chunks: 'async',
30
+ chunks: 'all',
31
+ // 2.3841858(MB)
32
+ minSize: 2500000,
33
+ // disable vendors~loadsh.js...
34
+ cacheGroups: {
35
+ default: false,
36
+ defaultVendors: false,
37
+ },
38
+ },
39
+ };
40
+ return webpackOptimization;
41
+ };
@@ -1 +1,35 @@
1
- import{join}from"node:path";import{getBundleFileName}from"../helpers/get-bundle-file-name.js";import{resolvePublicPath}from"./resolve-public-path.js";export const createOutput=async(e,t,o)=>{const{projectCwd:n,webpack:a}=t,i=o[1],p=resolvePublicPath(t),u="function"==typeof a?.outputDir?await a.outputDir():a?.outputDir||"public";return{devtoolModuleFilenameTemplate:({namespace:e,resourcePath:t})=>`webpack:///${join(e,t)}`,environment:{},pathinfo:!1,path:join(n,u),publicPath:p,filename:`[name]/${getBundleFileName("js",e,a?.enableBundleHashName)}`,chunkFilename:"[id].[contenthash].js",...i.options?.output}};
1
+ import { join } from 'node:path';
2
+ import { getBundleFileName } from '../helpers/get-bundle-file-name.js';
3
+ import { resolvePublicPath } from './resolve-public-path.js';
4
+ export const createOutput = async (serveMode, evolveOptions, entryItem) => {
5
+ const { projectCwd, webpack } = evolveOptions;
6
+ const entryItemOption = entryItem[1];
7
+ // If we have customized publicPath, should be converted to `https://cdn.example.com/assets/`, `/assets/`
8
+ const publicPath = resolvePublicPath(evolveOptions);
9
+ // Allow us dynamic return `outputDir`, e.g dev_xxxx, we can create built directory via `branchName`
10
+ const outputDir = typeof webpack?.outputDir === 'function'
11
+ ? await webpack.outputDir()
12
+ : webpack?.outputDir || 'public';
13
+ const webpackOutput = {
14
+ // Formatting devtool sourcemap template file.
15
+ devtoolModuleFilenameTemplate: ({ namespace, resourcePath }) => {
16
+ return `webpack:///${join(namespace, resourcePath)}`;
17
+ },
18
+ // Replace output.ecmaVersion with output.environment and more detailed
19
+ environment: {},
20
+ // Include comments with information about the modules, Disable it can improved performance.
21
+ pathinfo: false,
22
+ // The output directory as an absolute path.
23
+ path: join(projectCwd, outputDir),
24
+ // The publicPath specifies the public URL address of the output files when referenced in a browser.
25
+ publicPath,
26
+ // Specifies the name of each output file on disk. You must not specify an absolute path here!
27
+ filename: `[name]/${getBundleFileName('js', serveMode, webpack?.enableBundleHashName)}`,
28
+ // hotUpdateMainFilename: '[runtime].[fullhash].hot-update.json',
29
+ // The filename of non-entry chunks as relative path inside the output.path directory.
30
+ chunkFilename: `[id].[contenthash].js`,
31
+ // Extends / overrides the default output configuration
32
+ ...entryItemOption.options?.output,
33
+ };
34
+ return webpackOutput;
35
+ };
@@ -1 +1,7 @@
1
- export const createPerformance=(n,e={})=>{const r={hints:!n&&"warning"};return Object.assign(r,e)};
1
+ export const createPerformance = (serveMode, performanceOptions = {}) => {
2
+ const basePerformance = {
3
+ // Disable entry size exceeds recommands warning for `serve` mode
4
+ hints: serveMode ? false : 'warning',
5
+ };
6
+ return Object.assign(basePerformance, performanceOptions);
7
+ };
@@ -1 +1,77 @@
1
- import{logger}from"@flatjs/common";import ReactRefreshWebpackPlugin from"@pmmmwh/react-refresh-webpack-plugin";import CaseSensitivePathsPlugin from"case-sensitive-paths-webpack-plugin";import ForkTsCheckerWebpackPlugin from"fork-ts-checker-webpack-plugin";import MiniCssExtractPlugin from"mini-css-extract-plugin";import webpack from"webpack";import{BundleAnalyzerPlugin}from"webpack-bundle-analyzer";import{enableBundleHashNameForModule}from"../helpers/enable-bundle-hashname-for-module.js";import{getBundleFileName}from"../helpers/get-bundle-file-name.js";import{shouldEnableReactFastRefresh}from"../helpers/should-enable-react-fast-refresh.js";import{createCircularDependencyPlugin}from"../plugins/circular-dependency/index.js";import{createCleanWebpackPlugin}from"../plugins/clean-webpack/index.js";import{createBuiltinDefineVariables}from"../plugins/define-variable/index.js";import{createModuleFederationPlugin}from"../plugins/module-federation/index.js";import{createHtmlPlugins}from"../plugins/multi-html/index.js";export const createPlugins=async(e,n,a)=>{const[r,i]=n,l=enableBundleHashNameForModule(a,i?.options),t=[new webpack.WatchIgnorePlugin({paths:[/\.d\.[cm]ts$/]}),new CaseSensitivePathsPlugin,...createCircularDependencyPlugin(e,a),new MiniCssExtractPlugin({filename:`[name]/${getBundleFileName("css",e,l)}`,chunkFilename:"[id].[contenthash].css"}),...await createBuiltinDefineVariables(e,a),...createCleanWebpackPlugin(e,n,a),...createModuleFederationPlugin(e,n,a),...createHtmlPlugins(e,n,a)],{analyzer:s,loaderOptions:o}=a,c=(n[1].entry||[]).find((e=>/.vue$/.test(e)));o.runTsChecker&&!c&&t.push(new ForkTsCheckerWebpackPlugin({async:e,typescript:{context:a.projectCwd,memoryLimit:8192}})),s&&t.push(new BundleAnalyzerPlugin({analyzerPort:"auto",analyzerMode:"server",...s}));const u=shouldEnableReactFastRefresh(e,n,a);u&&t.push(new ReactRefreshWebpackPlugin({overlay:!1})),!u&&e&&(a.devServer?.liveReload?logger.warn('The HMR disabled cause of "liveReload" specificed'):logger.warn(`The HMR disabled cause of \`"moduleFederation":"${r}"\``));const p=a.webpack?.plugins||[];return t.concat(p)};
1
+ import { logger } from '@flatjs/common';
2
+ import ReactRefreshWebpackPlugin from '@pmmmwh/react-refresh-webpack-plugin';
3
+ import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
4
+ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
5
+ import webpack from 'webpack';
6
+ import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
7
+ import { enableBundleHashNameForModule } from '../helpers/enable-bundle-hashname-for-module.js';
8
+ import { getBundleFileName } from '../helpers/get-bundle-file-name.js';
9
+ import { shouldEnableReactFastRefresh } from '../helpers/should-enable-react-fast-refresh.js';
10
+ import { createCircularDependencyPlugin } from '../plugins/circular-dependency/index.js';
11
+ import { createCleanWebpackPlugin } from '../plugins/clean-webpack/index.js';
12
+ import { createBuiltinDefineVariables } from '../plugins/define-variable/index.js';
13
+ import { createModuleFederationPlugin } from '../plugins/module-federation/index.js';
14
+ import { createHtmlPlugins } from '../plugins/multi-html/index.js';
15
+ import { createTsCheckerPlugins } from '../plugins/ts-checker/index.js';
16
+ export const createPlugins = async (serveMode, entryMapItem, evolveOptions) => {
17
+ const [entryName, entryItemOption] = entryMapItem;
18
+ const bundleHashNameEnabled = enableBundleHashNameForModule(evolveOptions, entryItemOption?.options);
19
+ const builtInPlugins = [
20
+ // Because TS will may generate .js and .d.ts files, you should ignore these files,
21
+ // otherwise watchers may go into an infinite watch loop.
22
+ new webpack.WatchIgnorePlugin({
23
+ paths: [/\.d\.[cm]ts$/],
24
+ }),
25
+ // Case Sensitive Paths for OSX
26
+ new CaseSensitivePathsPlugin(),
27
+ // Detect modules with circular dependencies when bundling with webpack for `development` mode.
28
+ ...createCircularDependencyPlugin(serveMode, evolveOptions),
29
+ // For css minify extractor, Note `"sideEffects": false,` of `package.json` will not emits a file (writes a file to the filesystem)
30
+ new MiniCssExtractPlugin({
31
+ // Options similar to the same options in webpackOptions.output
32
+ // both options are optional
33
+ filename: `[name]/${getBundleFileName('css', serveMode, bundleHashNameEnabled)}`,
34
+ // the chunkFilename option can be a function for webpack@5
35
+ chunkFilename: '[id].[contenthash].css',
36
+ }),
37
+ // create builtin DefinePlugin
38
+ ...(await createBuiltinDefineVariables(serveMode, evolveOptions)),
39
+ // clean webpack plugin
40
+ ...createCleanWebpackPlugin(serveMode, entryMapItem, evolveOptions),
41
+ // Put ModuleFederationPlugin before html webpack plugin.
42
+ ...createModuleFederationPlugin(serveMode, entryMapItem, evolveOptions),
43
+ // Create all need html plugins
44
+ ...createHtmlPlugins(serveMode, entryMapItem, evolveOptions),
45
+ // Create all need ts-checker plugins
46
+ ...createTsCheckerPlugins(serveMode, entryMapItem, evolveOptions),
47
+ ];
48
+ // Analyze an existing bundle, if allowed.
49
+ if (evolveOptions.analyzer) {
50
+ builtInPlugins.push(new BundleAnalyzerPlugin({
51
+ analyzerPort: 'auto',
52
+ analyzerMode: 'server',
53
+ ...evolveOptions.analyzer,
54
+ }));
55
+ }
56
+ // Indicates current we use `hot` mode for `webpack-dev-server` hot reload true.
57
+ const enabledHmr = shouldEnableReactFastRefresh(serveMode, entryMapItem, evolveOptions);
58
+ if (enabledHmr) {
59
+ // Applies the react-refresh Babel plugin on non-production modes only
60
+ // Ensure `react-refresh/runtime` is hoisted and shared
61
+ // https://github.com/pmmmwh/react-refresh-webpack-plugin/blob/main/docs/TROUBLESHOOTING.md#externalising-react
62
+ builtInPlugins.push(new ReactRefreshWebpackPlugin({
63
+ // Always use webpack-dev-server `client` overlay!
64
+ overlay: false,
65
+ }));
66
+ }
67
+ if (!enabledHmr && serveMode) {
68
+ if (evolveOptions.devServer?.liveReload) {
69
+ logger.warn(`The HMR disabled cause of "liveReload" specificed`);
70
+ }
71
+ else {
72
+ logger.warn(`The HMR disabled cause of \`"moduleFederation":"${entryName}"\``);
73
+ }
74
+ }
75
+ const extraPlugins = evolveOptions.webpack?.plugins || [];
76
+ return builtInPlugins.concat(extraPlugins);
77
+ };
@@ -1 +1,37 @@
1
- import{join}from"node:path";import{mergeOptions}from"@flatjs/common";import{TsconfigPathsPlugin}from"tsconfig-paths-webpack-plugin";export const createResolve=(s,o)=>{const n={mainFields:["browser","module","main"],extensions:[".ts",".tsx",".js",".json"],extensionAlias:{".js":[".js",".ts"],".cjs":[".cjs",".cts"],".mjs":[".mjs",".mts"],".jsx":[".jsx",".tsx"]},plugins:[new TsconfigPathsPlugin({configFile:join(s,"tsconfig.json"),extensions:[".ts",".tsx",".js",".jsx"]})]};return mergeOptions(n,o?.resolve||{})};
1
+ /* eslint-disable @typescript-eslint/naming-convention */
2
+ import { join } from 'node:path';
3
+ import { mergeOptions } from '@flatjs/common';
4
+ import { TsconfigPathsPlugin } from 'tsconfig-paths-webpack-plugin';
5
+ export const createResolve = (projectCwd, webpackOptions) => {
6
+ const resolve = {
7
+ mainFields: ['browser', 'module', 'main'],
8
+ // Add `.ts` and `.tsx` as a resolvable extension.
9
+ extensions: ['.ts', '.tsx', '.js', '.json'],
10
+ // Add support for TypeScripts fully qualified ESM imports.
11
+ extensionAlias: {
12
+ '.js': ['.js', '.ts'],
13
+ '.cjs': ['.cjs', '.cts'],
14
+ '.mjs': ['.mjs', '.mts'],
15
+ '.jsx': ['.jsx', '.tsx'],
16
+ },
17
+ plugins: [
18
+ // Resolve modules according to baseUrl and paths in your tsconfig.json.
19
+ // https://www.npmjs.com/package/tsconfig-paths-webpack-plugin
20
+ // FIXME: Don't support `moduleResolution:nodenext`, for now support `moduleResolution:node`
21
+ // All alias import don't include suffix e.g. `.js`
22
+ // 1. correct `import { x } from '@/utils/str`
23
+ // 2. wrong `import { x } from '@/utils/str.js`
24
+ // 3. it will also help `less-loader` to support `@import` directly no additional `resolve.alias` setup
25
+ // @import '~@/utils/xxx.less'
26
+ // @import url('./child.less');
27
+ // @import url('~@/react/less/alias.less');
28
+ // @import '~@/react/less/alias2.less';
29
+ // @import '~@/utils/shared.less';
30
+ new TsconfigPathsPlugin({
31
+ configFile: join(projectCwd, 'tsconfig.json'),
32
+ extensions: ['.ts', '.tsx', '.js', '.jsx'],
33
+ }),
34
+ ],
35
+ };
36
+ return mergeOptions(resolve, webpackOptions?.resolve || {});
37
+ };
@@ -1 +1,19 @@
1
- import{ruleAssets}from"./rule-sets/rule-assets.js";import{ruleCss}from"./rule-sets/rule-css.js";import{ruleLess}from"./rule-sets/rule-less.js";import{ruleScripts}from"./rule-sets/rule-scripts.js";import{ruleSvgIcon}from"./rule-sets/rule-svg-icon.js";export const createRuleSets=(s,e,r)=>{const l=[ruleSvgIcon(),ruleAssets(e,r),ruleCss(s,e,r,!1),ruleCss(s,e,r,!0),ruleLess(s,e,r),ruleScripts(s,e,r)],t=r.webpack?.ruleSets||[];return l.concat(t)};
1
+ import { ruleAssets } from './rule-sets/rule-assets.js';
2
+ import { ruleCss } from './rule-sets/rule-css.js';
3
+ import { ruleLess } from './rule-sets/rule-less.js';
4
+ import { ruleScripts } from './rule-sets/rule-scripts.js';
5
+ import { ruleSvgIcon } from './rule-sets/rule-svg-icon.js';
6
+ export const createRuleSets = (serveMode, entryMapItem, evolveOptions) => {
7
+ const rules = [
8
+ ruleSvgIcon(),
9
+ ruleAssets(entryMapItem, evolveOptions),
10
+ // normal css style.
11
+ ruleCss(serveMode, entryMapItem, evolveOptions, false),
12
+ // css module style. xxx.module.css
13
+ ruleCss(serveMode, entryMapItem, evolveOptions, true),
14
+ ruleLess(serveMode, entryMapItem, evolveOptions),
15
+ ruleScripts(serveMode, entryMapItem, evolveOptions),
16
+ ];
17
+ const extraRuleSets = evolveOptions.webpack?.ruleSets || [];
18
+ return rules.concat(extraRuleSets);
19
+ };
@@ -1 +1,56 @@
1
- import{assertOnlySingleEntryItem}from"../helpers/assert-only-single-entry-item.js";import{createExternals}from"./create-externals.js";import{createOptimization}from"./create-optimization.js";import{createOutput}from"./create-output.js";import{createPerformance}from"./create-performance.js";import{createPlugins}from"./create-plugins.js";import{createResolve}from"./create-resolve.js";import{createRuleSets}from"./create-rule-sets.js";export const loadWebpackConfig=async(e,t,r)=>{const a="development"===e,{projectCwd:o,webpack:s,devServer:n}=r,c=n?.watchOptions,i=assertOnlySingleEntryItem(t,r),m=createRuleSets(a,i,r);return{mode:e,plugins:await createPlugins(a,i,r),watchOptions:c,output:await createOutput(a,r,i),context:o,target:s?.target??["web","es5"],resolve:createResolve(o,s),module:{rules:m},devtool:a?"eval-source-map":s?.sourceMap||!1,externalsType:s?.externalsType,externals:createExternals(s?.externals,i),performance:createPerformance(a,s?.performance),optimization:createOptimization(a,r,i),infrastructureLogging:s?.infrastructureLogging??{level:"warn"},stats:s?.stats??{preset:"minimal"},cache:{type:"memory"}}};
1
+ import { assertOnlySingleEntryItem } from '../helpers/assert-only-single-entry-item.js';
2
+ import { createExternals } from './create-externals.js';
3
+ import { createOptimization } from './create-optimization.js';
4
+ import { createOutput } from './create-output.js';
5
+ import { createPerformance } from './create-performance.js';
6
+ import { createPlugins } from './create-plugins.js';
7
+ import { createResolve } from './create-resolve.js';
8
+ import { createRuleSets } from './create-rule-sets.js';
9
+ /**
10
+ * Try to organization the configuraiton object of `webpack`
11
+ * @param mode Enable production optimizations or development hints.
12
+ * @param entryMap The only single one `servedEntry` or `toBuildEntry`
13
+ * @param overrideOptions The manually override configuration options for flatjsEvolve
14
+ */
15
+ export const loadWebpackConfig = async (mode, entryMap, evolveOptions) => {
16
+ const serveMode = mode === 'development';
17
+ const { projectCwd, webpack, devServer } = evolveOptions;
18
+ const watchOptions = devServer?.watchOptions;
19
+ const singleEntryItem = assertOnlySingleEntryItem(entryMap, evolveOptions);
20
+ const moduleRules = createRuleSets(serveMode, singleEntryItem, evolveOptions);
21
+ const plugins = await createPlugins(serveMode, singleEntryItem, evolveOptions);
22
+ const output = await createOutput(serveMode, evolveOptions, singleEntryItem);
23
+ const webpackConfig = {
24
+ mode,
25
+ plugins,
26
+ watchOptions,
27
+ output,
28
+ // The base directory, an absolute path, for resolving entry points and loaders from configuration.
29
+ // The context is an absolute string to the directory that contains the entry files.
30
+ context: projectCwd,
31
+ target: webpack?.target ?? ['web', 'es5'],
32
+ resolve: createResolve(projectCwd, webpack),
33
+ module: { rules: moduleRules },
34
+ devtool: serveMode ? 'eval-source-map' : webpack?.sourceMap || false,
35
+ externalsType: webpack?.externalsType,
36
+ // It's globally external configurations for all entries, if we need to specificed externals for each entry.
37
+ // Simply move it into entry options.
38
+ externals: createExternals(webpack?.externals, singleEntryItem),
39
+ performance: createPerformance(serveMode, webpack?.performance),
40
+ optimization: createOptimization(serveMode, evolveOptions, singleEntryItem),
41
+ // Setup logging level for `infrastructure` like. `webpack-dev-server`
42
+ infrastructureLogging: webpack?.infrastructureLogging ?? {
43
+ level: 'warn',
44
+ },
45
+ stats: webpack?.stats ?? {
46
+ preset: 'minimal',
47
+ },
48
+ cache: {
49
+ // Use `filesystem` cache to improve performance for `production` build
50
+ // Default cache directory is `node_modules/.cache`
51
+ // type: serveMode ? 'memory' : 'filesystem',
52
+ type: 'memory',
53
+ },
54
+ };
55
+ return webpackConfig;
56
+ };
@@ -1 +1,15 @@
1
- import{ensureSlash}from"@flatjs/common";export const resolvePublicPath=t=>{const{webpack:a}=t;let e="auto";return a?.publicPath&&"auto"!==a.publicPath&&(e=ensureSlash(a.publicPath,!0)),e};
1
+ import { ensureSlash } from '@flatjs/common';
2
+ /**
3
+ * Try to normalize publicPath, if we have customized publicPath, should be converted to `https://cdn.example.com/assets/`, `/assets/`
4
+ * @param evolveOptions
5
+ * @returns `auto` or customizd publicPath
6
+ */
7
+ export const resolvePublicPath = (evolveOptions) => {
8
+ const { webpack } = evolveOptions;
9
+ let publicPath = 'auto';
10
+ // If we have customized publicPath, should be converted to `https://cdn.example.com/assets/`, `/assets/`
11
+ if (webpack?.publicPath && webpack.publicPath !== 'auto') {
12
+ publicPath = ensureSlash(webpack.publicPath, true);
13
+ }
14
+ return publicPath;
15
+ };
@@ -1 +1,3 @@
1
- export const ICON_PATH_REGEX=/svg-icons\//;export const IMAGE_PATH_REGEX=/\.(?:jpe?g|png|gif|svg)$/;export const FONT_PATH_REGEX=/\.(?:ttf|eot|woff|woff2)(?:\?.+)?$/;
1
+ export const ICON_PATH_REGEX = /svg-icons\//;
2
+ export const IMAGE_PATH_REGEX = /\.(?:jpe?g|png|gif|svg)$/;
3
+ export const FONT_PATH_REGEX = /\.(?:ttf|eot|woff|woff2)(?:\?.+)?$/;
@@ -1 +1,50 @@
1
- import{dirname,join,relative,resolve}from"node:path";import{resolvePublicPath}from"../resolve-public-path.js";import{FONT_PATH_REGEX,IMAGE_PATH_REGEX}from"./constants.js";import{isIconSvg}from"./rule-utils.js";const getEntryAssetFileName=(e,t,r)=>{const[s,o]=t,{projectCwd:a,projectVirtualPath:i}=r;let n=dirname(join(i,e.replace(/^src/,"")));const l=o.entry.map((e=>dirname(join(a,e)))),m=resolve(a,e),c=l.find((e=>m.startsWith(e)));return c&&(n=dirname(join(s,relative(c,m)))),`${n}/[name]-[contenthash:8][ext]`};export const ruleAssets=(e,t)=>{const r=resolvePublicPath(t);return{type:"asset",test:e=>FONT_PATH_REGEX.test(e)||IMAGE_PATH_REGEX.test(e)&&!isIconSvg(e),generator:{filename:({filename:r})=>getEntryAssetFileName(r,e,t),publicPath:"auto"===r?void 0:r},parser:{dataUrlCondition:{maxSize:t.loaderOptions.assetDataUrlMaxSize}}}};
1
+ import { dirname, join, relative, resolve } from 'node:path';
2
+ import { resolvePublicPath } from '../resolve-public-path.js';
3
+ import { FONT_PATH_REGEX, IMAGE_PATH_REGEX } from './constants.js';
4
+ import { isIconSvg } from './rule-utils.js';
5
+ const getEntryAssetFileName = (filename, entryMapItem, evolveOptions) => {
6
+ const [entryName, entryConfig] = entryMapItem;
7
+ const { projectCwd, projectVirtualPath } = evolveOptions;
8
+ let assetBase = dirname(join(projectVirtualPath, filename.replace(/^src/, '')));
9
+ const entryDirs = entryConfig.entry.map((file) => dirname(join(projectCwd, file)));
10
+ const assetAbsName = resolve(projectCwd, filename);
11
+ const matchedEntryDir = entryDirs.find((s) => assetAbsName.startsWith(s));
12
+ if (matchedEntryDir) {
13
+ assetBase = dirname(join(entryName, relative(matchedEntryDir, assetAbsName)));
14
+ }
15
+ return `${assetBase}/[name]-[contenthash:8][ext]`;
16
+ };
17
+ /**
18
+ * Preparing image loader for normal pictures except stored in folder `icons`
19
+ * Webpack@5 don't need `file-loader`, `raw-loader`, `url-loader` provider us `asset-modules`
20
+ * https://webpack.js.org/guides/asset-modules/
21
+ * @param entryItem The available entries, `development` it contains multiple enties, `production` only one entry in once build.
22
+ */
23
+ export const ruleAssets = (entryItem, evolveOptions) => {
24
+ // If we have customized publicPath, should be converted to `https://cdn.example.com/assets/`, `/assets/`
25
+ const publicPath = resolvePublicPath(evolveOptions);
26
+ const loader = {
27
+ type: 'asset',
28
+ test(resource) {
29
+ return (FONT_PATH_REGEX.test(resource) ||
30
+ (IMAGE_PATH_REGEX.test(resource) && !isIconSvg(resource)));
31
+ },
32
+ generator: {
33
+ // Rule.generator.filename is the same as output.assetModuleFilename and works only with asset and asset/resource module types.
34
+ filename({ filename }) {
35
+ return getEntryAssetFileName(filename, entryItem, evolveOptions);
36
+ },
37
+ // Make sure that we use production cdn for images avoid use `requireExtensions`
38
+ // NOTE: if `auto` we need to remove `publicPath` configuration leave it to undefined.
39
+ publicPath: publicPath === 'auto' ? undefined : publicPath,
40
+ },
41
+ parser: {
42
+ // Now webpack will automatically choose between resource and inline by following
43
+ // a default condition: a file with size less than 8kb will be treated as a inline module type and resource module type otherwise.
44
+ dataUrlCondition: {
45
+ maxSize: evolveOptions.loaderOptions.assetDataUrlMaxSize, // 4 * 1024, // 4kb
46
+ },
47
+ },
48
+ };
49
+ return loader;
50
+ };
@@ -1 +1,101 @@
1
- import{requireResolve}from"@flatjs/common";import{forgePostcssPluginPixel}from"@flatjs/forge-postcss-plugin-pixel";import cssnano from"cssnano";import MiniCssExtractPlugin from"mini-css-extract-plugin";import{allowPx2remForModule}from"../../helpers/allow-px2rem-for-module.js";const getPostcssOptions=(s,o={},e={})=>{const r=[...e.plugins||[],cssnano({preset:["default",{discardComments:{removeAll:!s},reduceInitial:!1,normalizeWhitespace:!s,...e.cssnanoOptions}]})];return!1!==o&&r.push(forgePostcssPluginPixel(o)),{plugins:r}};export const ruleCss=(s,o,e,r=!1)=>{const{pixelOptions:t,cssLoaderOptions:i={},postcssOptions:l}=e.loaderOptions,n=r?{}:{modules:!1},p={test:/\.css$/i,use:[{loader:MiniCssExtractPlugin.loader,options:{esModule:!0}},{loader:requireResolve(import.meta.url,"css-loader"),options:{sourceMap:s,...i,...n}}]};r?p.include=/\.module\.css$/i:p.exclude=/\.module\.css$/i;const c=allowPx2remForModule(o,e);if(Array.isArray(p.use)){const o=getPostcssOptions(s,!!c&&t,l);p.use.push({loader:requireResolve(import.meta.url,"postcss-loader"),options:{postcssOptions:{...o,config:!1},sourceMap:s}})}return p};
1
+ import { requireResolve } from '@flatjs/common';
2
+ import { forgePostcssPluginPixel, } from '@flatjs/forge-postcss-plugin-pixel';
3
+ import cssnano from 'cssnano';
4
+ import MiniCssExtractPlugin from 'mini-css-extract-plugin';
5
+ import { allowPx2remForModule } from '../../helpers/allow-px2rem-for-module.js';
6
+ /**
7
+ * Normalize postcss-loader options.
8
+ * @param serveMode The value indicates if we are in `built` or `serve` mode.
9
+ * @param pixelOptions The pixel options of `postcss` plugin
10
+ * @param cssnanoOptions The configuration rules for `cssnano`
11
+ */
12
+ const getPostcssOptions = (serveMode, pixelOptions = {}, postcssOptions = {}) => {
13
+ // Use cssnano to minify css styles.
14
+ // https://cssnano.co/docs/config-file
15
+ const postCssPlugins = [
16
+ ...(postcssOptions.plugins || []),
17
+ cssnano({
18
+ // https://www.npmjs.com/package/cssnano-preset-default
19
+ // Note Advanced optimisations for cssnano; may or may not break your CSS!
20
+ // `Antd` was broken while use `advanced` preset.:(
21
+ preset: [
22
+ 'default',
23
+ {
24
+ discardComments: {
25
+ removeAll: !serveMode,
26
+ },
27
+ // throw new error `Please provide a proper feature name. Cannot find css-initial-value`
28
+ // disable this plugin `postcss-reduce-initial` via reduceInitial: false
29
+ // disable this plugin `postcss-minify-font-values` via minifyFontValues:false
30
+ reduceInitial: false,
31
+ // minifyFontValues: false,
32
+ normalizeWhitespace: !serveMode,
33
+ // allow us override cssnano configuration rules.
34
+ ...postcssOptions.cssnanoOptions,
35
+ },
36
+ ],
37
+ }),
38
+ ];
39
+ if (pixelOptions !== false) {
40
+ postCssPlugins.push(forgePostcssPluginPixel(pixelOptions));
41
+ }
42
+ return {
43
+ plugins: postCssPlugins,
44
+ };
45
+ };
46
+ /**
47
+ * Actually, style-loader is the one that is responsible for CSS HMR
48
+ * https://github.com/webpack-contrib/style-loader/blob/master/src/index.js#L31-L42
49
+ * @param serveMode
50
+ * @param entryMapItem
51
+ * @param evolveOptions `builtin` loaders
52
+ */
53
+ export const ruleCss = (serveMode, entryMapItem, evolveOptions, useCssModule = false) => {
54
+ // The value indicates we will enable px2rem using `@flatjs/forge-postcss-plugin-pixel`
55
+ const { pixelOptions, cssLoaderOptions = {}, postcssOptions, } = evolveOptions.loaderOptions;
56
+ // automatically enable css modules for files with .module.css extension
57
+ const cssLoaderOfCssModules = !useCssModule ? { modules: false } : {};
58
+ const ruleSet = {
59
+ test: /\.css$/i,
60
+ use: [
61
+ {
62
+ loader: MiniCssExtractPlugin.loader,
63
+ options: {
64
+ // https://github.com/webpack-contrib/mini-css-extract-plugin/releases/tag/v1.0.0
65
+ // https://github.com/webpack-contrib/css-loader/blob/master/README.md#modules
66
+ esModule: true,
67
+ },
68
+ },
69
+ {
70
+ loader: requireResolve(import.meta.url, 'css-loader'),
71
+ options: {
72
+ sourceMap: serveMode,
73
+ ...cssLoaderOptions,
74
+ ...cssLoaderOfCssModules,
75
+ },
76
+ },
77
+ ],
78
+ };
79
+ if (useCssModule) {
80
+ ruleSet.include = /\.module\.css$/i;
81
+ }
82
+ else {
83
+ ruleSet.exclude = /\.module\.css$/i;
84
+ }
85
+ const isAllowPx2Rem = allowPx2remForModule(entryMapItem, evolveOptions);
86
+ if (Array.isArray(ruleSet.use)) {
87
+ const postCssOption = getPostcssOptions(serveMode, isAllowPx2Rem ? pixelOptions : false, postcssOptions);
88
+ ruleSet.use.push({
89
+ loader: requireResolve(import.meta.url, 'postcss-loader'),
90
+ options: {
91
+ postcssOptions: {
92
+ ...postCssOption,
93
+ // Removes the need to lookup and load external config files ( `postcss.config.cjs`...) multiple times during compilation.
94
+ config: false,
95
+ },
96
+ sourceMap: serveMode,
97
+ },
98
+ });
99
+ }
100
+ return ruleSet;
101
+ };
@@ -1 +1,44 @@
1
- import{requireResolve}from"@flatjs/common";import{ruleCss}from"./rule-css.js";export const ruleLess=(s,e,r)=>{const o=ruleCss(s,e,r);o.test=/\.less$/i;const t=r.loaderOptions.lessOptions;return Array.isArray(o.use)&&o.use.push({loader:requireResolve(import.meta.url,"less-loader"),options:{sourceMap:s,lessOptions:{sourceMap:s,javascriptEnabled:!0,...t}}}),o};
1
+ import { requireResolve } from '@flatjs/common';
2
+ import { ruleCss } from './rule-css.js';
3
+ /**
4
+ * Preparing configurations for `less-loader`
5
+ * @param serveMode The value indicates if we are in `built` or `serve` mode.
6
+ * @param pluginLoaderOptions `builtin` loaders
7
+ * @example
8
+ * ```ts
9
+ * `~` makes the url an module
10
+ * webpack: {
11
+ * externals: {
12
+ * antd: 'antd',
13
+ * dayjs: 'dayjs',
14
+ * },
15
+ * resolve: {
16
+ * alias: {
17
+ * '@': resolve(projectCwd, './src'),
18
+ * },
19
+ * },
20
+ * },
21
+ * `@import '~@/theme/default.less';` at `src/theme/default.less`
22
+ *
23
+ * ```
24
+ */
25
+ export const ruleLess = (serveMode, entryMapItem, evolveOptions) => {
26
+ const ruleSet = ruleCss(serveMode, entryMapItem, evolveOptions);
27
+ ruleSet.test = /\.less$/i;
28
+ // The Options for Less.
29
+ const lessOptions = evolveOptions.loaderOptions.lessOptions;
30
+ if (Array.isArray(ruleSet.use)) {
31
+ ruleSet.use.push({
32
+ loader: requireResolve(import.meta.url, 'less-loader'),
33
+ options: {
34
+ sourceMap: serveMode,
35
+ lessOptions: {
36
+ sourceMap: serveMode,
37
+ javascriptEnabled: true,
38
+ ...lessOptions,
39
+ },
40
+ },
41
+ });
42
+ }
43
+ return ruleSet;
44
+ };
@@ -1 +1,34 @@
1
- import{requireResolve}from"@flatjs/common";import{mergeBabelOption}from"../../helpers/merge-babel-options.js";import{shouldEnableReactFastRefresh}from"../../helpers/should-enable-react-fast-refresh.js";export const ruleScripts=(e,r,s)=>{const{babelOptions:o={},modularImports:t=[]}=s.loaderOptions,l=mergeBabelOption(t,o);shouldEnableReactFastRefresh(e,r,s)&&(l.plugins?l.plugins.push(requireResolve(import.meta.url,"react-refresh/babel")):l.plugins=[requireResolve(import.meta.url,"react-refresh/babel")]);return{test:/\.(tsx|ts|js|jsx)$/,use:[{loader:requireResolve(import.meta.url,"babel-loader"),options:l}]}};
1
+ import { requireResolve } from '@flatjs/common';
2
+ import { mergeBabelOption } from '../../helpers/merge-babel-options.js';
3
+ import { shouldEnableReactFastRefresh } from '../../helpers/should-enable-react-fast-refresh.js';
4
+ export const ruleScripts = (serveMode, entryMapItem, evolveOptions) => {
5
+ const { babelOptions = {}, modularImports = [] } = evolveOptions.loaderOptions;
6
+ const finnalBabelOptions = mergeBabelOption(modularImports, babelOptions);
7
+ // Indicates current we use `hot` mode for `webpack-dev-server` hot reload true.
8
+ const enabledHmr = shouldEnableReactFastRefresh(serveMode, entryMapItem, evolveOptions);
9
+ // 针对react 自动注入`react-refresh/babel`
10
+ if (enabledHmr) {
11
+ if (finnalBabelOptions.plugins) {
12
+ finnalBabelOptions.plugins.push(requireResolve(import.meta.url, 'react-refresh/babel'));
13
+ }
14
+ else {
15
+ finnalBabelOptions.plugins = [
16
+ requireResolve(import.meta.url, 'react-refresh/babel'),
17
+ ];
18
+ }
19
+ }
20
+ const loader = {
21
+ // use `vue-loader` to handle .vue here.
22
+ // test: /\.(tsx|ts|js|jsx|vue)$/,
23
+ test: /\.(tsx|ts|js|jsx)$/,
24
+ // Don't exclude anythings because of we need to import node_modules from `@flatjs`
25
+ // exclude: /(node_modules|bower_components)/,
26
+ use: [
27
+ {
28
+ loader: requireResolve(import.meta.url, 'babel-loader'),
29
+ options: finnalBabelOptions,
30
+ },
31
+ ],
32
+ };
33
+ return loader;
34
+ };
@@ -1 +1,25 @@
1
- import{getDirname}from"@armit/file-utility";import{isIconSvg}from"./rule-utils.js";export const ruleSvgIcon=()=>({test:e=>isIconSvg(e),use:[{loader:getDirname(import.meta.url,"../../loaders/loader-icon.cjs"),options:{svgo:{plugins:[{name:"removeTitle"},{name:"removeDimensions"}]}}}]});
1
+ import { getDirname } from '@armit/file-utility';
2
+ import { isIconSvg } from './rule-utils.js';
3
+ /**
4
+ * Preparing svg loader for `icons`
5
+ * Note we must be put all *.svg into folder `icons`
6
+ */
7
+ export const ruleSvgIcon = () => {
8
+ const loader = {
9
+ test(resource) {
10
+ return isIconSvg(resource);
11
+ },
12
+ use: [
13
+ {
14
+ // FIXME: we need to always keep the directory structures here to make sure correct loader path resolve.
15
+ loader: getDirname(import.meta.url, '../../loaders/loader-icon.cjs'),
16
+ options: {
17
+ svgo: {
18
+ plugins: [{ name: 'removeTitle' }, { name: 'removeDimensions' }],
19
+ },
20
+ },
21
+ },
22
+ ],
23
+ };
24
+ return loader;
25
+ };