From 056093168d70286979c44ea597099ad1bf1c5793 Mon Sep 17 00:00:00 2001 From: Gengkun Date: Mon, 11 Sep 2023 11:49:39 +0800 Subject: [PATCH 01/49] fix: export client dir in react-refresh-plugin (#4164) --- packages/rspack-plugin-react-refresh/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/rspack-plugin-react-refresh/package.json b/packages/rspack-plugin-react-refresh/package.json index bde2c1bd0e8..761f2ae2b66 100644 --- a/packages/rspack-plugin-react-refresh/package.json +++ b/packages/rspack-plugin-react-refresh/package.json @@ -13,6 +13,7 @@ "test": "echo success" }, "files": [ + "client", "src" ], "publishConfig": { From 25df2981ce1f0232ab05109c0995a249f57e2a09 Mon Sep 17 00:00:00 2001 From: underfin Date: Mon, 11 Sep 2023 11:55:41 +0800 Subject: [PATCH 02/49] fix: resolve async css chunk loading promise (#4165) --- .../runtime/css_loading_with_loading.js | 4 ++- .../cases/react/basic/index.test.ts | 1 + .../playground/cases/react/basic/src/App.jsx | 29 +++++++++++-------- .../cases/react/basic/src/LazyComponent.css | 0 .../cases/react/basic/src/LazyComponent.jsx | 7 +++++ 5 files changed, 28 insertions(+), 13 deletions(-) create mode 100644 packages/playground/cases/react/basic/src/LazyComponent.css create mode 100644 packages/playground/cases/react/basic/src/LazyComponent.jsx diff --git a/crates/rspack_plugin_runtime/src/runtime_module/runtime/css_loading_with_loading.js b/crates/rspack_plugin_runtime/src/runtime_module/runtime/css_loading_with_loading.js index 1f2aecd3caf..636ae7d5ca4 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/runtime/css_loading_with_loading.js +++ b/crates/rspack_plugin_runtime/src/runtime_module/runtime/css_loading_with_loading.js @@ -60,7 +60,9 @@ var loadCssChunkCallback = function (parentChunkLoadingFunction, data) { var chunkIds = data[0]; if (parentChunkLoadingFunction) parentChunkLoadingFunction(data); for (var i = 0; i < chunkIds.length; i++) { - installedChunks[chunkIds[i]] = 0; + if (installedChunks[chunkIds[i]] === undefined) { + installedChunks[chunkIds[i]] = 0; + } } }; var chunkLoadingGlobal = $CHUNK_LOADING_GLOBAL_EXPR$ = $CHUNK_LOADING_GLOBAL_EXPR$ || []; diff --git a/packages/playground/cases/react/basic/index.test.ts b/packages/playground/cases/react/basic/index.test.ts index a6a420c194b..33fefe02749 100644 --- a/packages/playground/cases/react/basic/index.test.ts +++ b/packages/playground/cases/react/basic/index.test.ts @@ -2,6 +2,7 @@ import { test, expect } from "@/fixtures"; test("render should work", async ({ page }) => { expect(await page.textContent(".header")).toBe("Hello World"); + expect(await page.textContent("#lazy-component")).toBe("Lazy Component"); }); test("hmr should work", async ({ page, fileAction, rspack }) => { diff --git a/packages/playground/cases/react/basic/src/App.jsx b/packages/playground/cases/react/basic/src/App.jsx index 229770f9d16..a72ff3a972a 100644 --- a/packages/playground/cases/react/basic/src/App.jsx +++ b/packages/playground/cases/react/basic/src/App.jsx @@ -1,25 +1,30 @@ -import React from "react"; -import "./index.css"; -import { ContextComponent } from "./CountProvider"; -import { ReactRefreshFinder } from "./ReactRefreshFinder"; +import React from 'react' +import './index.css' +import { ContextComponent } from './CountProvider' +import { ReactRefreshFinder } from './ReactRefreshFinder' import { SameExportName as SameExportName1 } from './SameExportName1' import { SameExportName as SameExportName2 } from './SameExportName2' const Button = () => { - const [count, setCount] = React.useState(10); - return ; -}; + const [count, setCount] = React.useState(10) + return +} + +const LazyComponent = React.lazy(() => import('./LazyComponent')) export const App = () => { return ( -
-
Hello World
+
+
Hello World
}> + +
- ); -}; + ) +} diff --git a/packages/playground/cases/react/basic/src/LazyComponent.css b/packages/playground/cases/react/basic/src/LazyComponent.css new file mode 100644 index 00000000000..e69de29bb2d diff --git a/packages/playground/cases/react/basic/src/LazyComponent.jsx b/packages/playground/cases/react/basic/src/LazyComponent.jsx new file mode 100644 index 00000000000..65545394690 --- /dev/null +++ b/packages/playground/cases/react/basic/src/LazyComponent.jsx @@ -0,0 +1,7 @@ +import './LazyComponent.css' + +function LazyComponent () { + return
Lazy Component
+} + +export default LazyComponent From 509abcfc523bc20125459f5d428dc1645751700c Mon Sep 17 00:00:00 2001 From: Gengkun Date: Mon, 11 Sep 2023 14:54:27 +0800 Subject: [PATCH 03/49] chore: add profile syntax comment (#4166) --- packages/rspack-cli/src/utils/profile.ts | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/packages/rspack-cli/src/utils/profile.ts b/packages/rspack-cli/src/utils/profile.ts index 0fd45650da5..f3e293e1fde 100644 --- a/packages/rspack-cli/src/utils/profile.ts +++ b/packages/rspack-cli/src/utils/profile.ts @@ -1,3 +1,36 @@ +/* +The full syntax, remember update this when you change something in this file. + +`RSPACK_PROFILE='TRACE=filter=trace&output=./rspack.trace&layer=chrome|JSCPU=output=./rspack.jscpuprofile|LOGGING=output=./rspack.logging' rspack build` + ^----------------------------------------------: querystring syntax trace options + ^: | is a delimiter for different profile options + ^---------------------------------: querystring syntax js cpuprofile options + ^: | is a delimiter for different profile options + ^------------------------------: querystring syntax stats.logging options + ^-----------: trace filter, default to `trace`, more syntax: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#example-syntax + ^--------------------: trace output, `stderr`, `stdout`, or a file path, default to `./.rspack-profile-${timestamp}/trace.json` for layer `chrome` and default to `stdout` for layer `logger` + ^-----------: trace layer, `chrome` or `logger`, default to `chrome` + ^---------------------------: js cpuprofile output, `stderr`, `stdout`, or a file path, default to `./.rspack-profile-${timestamp}/jscpuprofile.json` + ^----------------------: stats.logging output, default to `./.rspack-profile-${timestamp}/logging.json` + +`RSPACK_PROFILE='TRACE=filter=trace&output=./rspack.trace&layer=chrome' rspack build`: only enable trace + +`RSPACK_PROFILE=TRACE rspack build`: only enable trace, and use default options for trace + +`RSPACK_PROFILE='JSCPU=output=./rspack.jscpuprofile' rspack build`: only enable js cpuprofile + +`RSPACK_PROFILE=JSCPU rspack build`: only enable js cpuprofile, and use default options for js cpuprofile + +`RSPACK_PROFILE='LOGGING=output=./rspack.logging' rspack build`: only enable stats.logging + +`RSPACK_PROFILE=LOGGING rspack build`: only enable stats.logging, and use default options for stats.logging + +`RSPACK_PROFILE=ALL rspack build`: enable all, and use default options + +`RSPACK_PROFILE=[rspack_node,rspack_core] rspack build`: enable all, but customize trace filter + +*/ + import inspector from "inspector"; import fs from "fs"; import path from "path"; From 94f04227b59c8476e9fa5ae400fe10557469fcc6 Mon Sep 17 00:00:00 2001 From: underfin Date: Mon, 11 Sep 2023 15:21:47 +0800 Subject: [PATCH 04/49] fix: chunkLoading false (#4167) --- .../src/chunk_graph/chunk_graph_module.rs | 9 ++--- .../src/dependency/worker/mod.rs | 2 +- .../runtime_module/load_chunk_with_module.rs | 37 ++++++++++--------- .../chunk-loading/false/dynamic.js | 1 + .../configCases/chunk-loading/false/index.js | 5 +++ .../chunk-loading/false/webpack.config.js | 5 +++ 6 files changed, 34 insertions(+), 25 deletions(-) create mode 100644 packages/rspack/tests/configCases/chunk-loading/false/dynamic.js create mode 100644 packages/rspack/tests/configCases/chunk-loading/false/index.js create mode 100644 packages/rspack/tests/configCases/chunk-loading/false/webpack.config.js diff --git a/crates/rspack_core/src/chunk_graph/chunk_graph_module.rs b/crates/rspack_core/src/chunk_graph/chunk_graph_module.rs index b7df2d255e8..e285f6da95d 100644 --- a/crates/rspack_core/src/chunk_graph/chunk_graph_module.rs +++ b/crates/rspack_core/src/chunk_graph/chunk_graph_module.rs @@ -151,14 +151,11 @@ impl ChunkGraph { &self, block: &ModuleIdentifier, chunk_group_by_ukey: &'a ChunkGroupByUkey, - ) -> &'a ChunkGroup { - let ukey = self + ) -> Option<&'a ChunkGroup> { + self .block_to_chunk_group_ukey .get(block) - .unwrap_or_else(|| panic!("Block({block:?}) doesn't have corresponding ChunkGroup")); - chunk_group_by_ukey - .get(ukey) - .unwrap_or_else(|| panic!("ChunkGroup({ukey:?}) doesn't exist")) + .and_then(|ukey| chunk_group_by_ukey.get(ukey)) } pub fn connect_block_and_chunk_group( diff --git a/crates/rspack_plugin_javascript/src/dependency/worker/mod.rs b/crates/rspack_plugin_javascript/src/dependency/worker/mod.rs index 7c81390a5bc..0955efb08e4 100644 --- a/crates/rspack_plugin_javascript/src/dependency/worker/mod.rs +++ b/crates/rspack_plugin_javascript/src/dependency/worker/mod.rs @@ -94,7 +94,7 @@ impl DependencyTemplate for WorkerDependency { let chunk_id = compilation .module_graph .module_identifier_by_dependency_id(&self.id) - .map(|module| { + .and_then(|module| { compilation .chunk_graph .get_block_chunk_group(module, &compilation.chunk_group_by_ukey) diff --git a/crates/rspack_plugin_runtime/src/runtime_module/load_chunk_with_module.rs b/crates/rspack_plugin_runtime/src/runtime_module/load_chunk_with_module.rs index 499f51aea0c..6545d11eec9 100644 --- a/crates/rspack_plugin_runtime/src/runtime_module/load_chunk_with_module.rs +++ b/crates/rspack_plugin_runtime/src/runtime_module/load_chunk_with_module.rs @@ -50,11 +50,11 @@ impl RuntimeModule for LoadChunkWithModuleRuntimeModule { let map = async_modules .par_iter() .filter_map(|identifier| { - let mut chunk_ids = { - let chunk_group = compilation - .chunk_graph - .get_block_chunk_group(identifier, &compilation.chunk_group_by_ukey); - chunk_group + if let Some(chunk_group) = compilation + .chunk_graph + .get_block_chunk_group(identifier, &compilation.chunk_group_by_ukey) + { + let mut chunk_ids = chunk_group .chunks .iter() .filter_map(|chunk_ukey| { @@ -68,21 +68,22 @@ impl RuntimeModule for LoadChunkWithModuleRuntimeModule { None } }) - .collect::>() - }; - if chunk_ids.is_empty() { - return None; - } - chunk_ids.sort_unstable(); - let module = compilation - .module_graph - .module_graph_module_by_identifier(identifier) - .expect("no module found"); + .collect::>(); + if chunk_ids.is_empty() { + return None; + } + chunk_ids.sort_unstable(); + let module = compilation + .module_graph + .module_graph_module_by_identifier(identifier) + .expect("no module found"); - let module_id = module.id(&compilation.chunk_graph); - let module_id_expr = serde_json::to_string(module_id).expect("invalid module_id"); + let module_id = module.id(&compilation.chunk_graph); + let module_id_expr = serde_json::to_string(module_id).expect("invalid module_id"); - Some((module_id_expr, chunk_ids)) + return Some((module_id_expr, chunk_ids)); + } + None }) .collect::>>(); diff --git a/packages/rspack/tests/configCases/chunk-loading/false/dynamic.js b/packages/rspack/tests/configCases/chunk-loading/false/dynamic.js new file mode 100644 index 00000000000..efeee5db16c --- /dev/null +++ b/packages/rspack/tests/configCases/chunk-loading/false/dynamic.js @@ -0,0 +1 @@ +export const value = 1; diff --git a/packages/rspack/tests/configCases/chunk-loading/false/index.js b/packages/rspack/tests/configCases/chunk-loading/false/index.js new file mode 100644 index 00000000000..bfc028bd499 --- /dev/null +++ b/packages/rspack/tests/configCases/chunk-loading/false/index.js @@ -0,0 +1,5 @@ +it("should work with chunk loading false", function () { + import("./dynamic").then(module => { + expect(module.value).toBe(1); + }); +}); diff --git a/packages/rspack/tests/configCases/chunk-loading/false/webpack.config.js b/packages/rspack/tests/configCases/chunk-loading/false/webpack.config.js new file mode 100644 index 00000000000..cf7c11451ba --- /dev/null +++ b/packages/rspack/tests/configCases/chunk-loading/false/webpack.config.js @@ -0,0 +1,5 @@ +module.exports = { + output: { + chunkLoading: false + } +}; From 77bada1db8eb32611de2a5ad6649ac3eaac25feb Mon Sep 17 00:00:00 2001 From: Gengkun Date: Mon, 11 Sep 2023 15:51:20 +0800 Subject: [PATCH 05/49] refactor: naming to RspackPlugin (#4156) * refactor: naming to RspackPlugin * lint * fix --- Cargo.lock | 1 - crates/node_binding/binding.d.ts | 170 +++++++++--------- .../src/options/raw_builtins/mod.rs | 125 +++++++------ .../src/options/raw_builtins/raw_banner.rs | 38 ++-- .../src/options/raw_builtins/raw_copy.rs | 24 +-- .../src/options/raw_builtins/raw_html.rs | 31 ++-- .../src/options/raw_builtins/raw_progress.rs | 8 +- .../raw_builtins/raw_swc_js_minimizer.rs | 38 ++-- .../src/options/raw_external.rs | 2 +- crates/rspack_core/Cargo.toml | 1 - crates/rspack_core/src/options/builtins.rs | 52 +----- crates/rspack_plugin_banner/src/lib.rs | 24 +-- crates/rspack_plugin_copy/src/lib.rs | 70 ++++++-- .../src/http_externals_plugin.rs | 2 +- crates/rspack_plugin_externals/src/lib.rs | 2 +- crates/rspack_plugin_html/src/config.rs | 36 ++-- crates/rspack_plugin_html/src/parser.rs | 6 +- crates/rspack_plugin_html/src/plugin.rs | 20 +-- .../rspack_plugin_html/src/visitors/asset.rs | 26 +-- crates/rspack_plugin_progress/src/lib.rs | 6 +- .../src/lib.rs | 6 +- .../rspack_plugin_swc_js_minimizer/src/lib.rs | 30 ++-- .../src/minify.rs | 4 +- crates/rspack_testing/src/test_config.rs | 8 +- .../tests/normalizeOptions.test.ts | 5 +- packages/rspack/src/Compiler.ts | 4 +- .../rspack/src/builtin-plugin/BannerPlugin.ts | 18 +- .../rspack/src/builtin-plugin/CopyPlugin.ts | 35 ---- .../src/builtin-plugin/CopyRspackPlugin.ts | 35 ++++ .../rspack/src/builtin-plugin/DefinePlugin.ts | 4 +- .../builtin-plugin/ElectronTargetPlugin.ts | 4 +- .../rspack/src/builtin-plugin/EntryPlugin.ts | 4 +- .../src/builtin-plugin/ExternalsPlugin.ts | 4 +- .../{HtmlPlugin.ts => HtmlRspackPlugin.ts} | 16 +- .../src/builtin-plugin/HttpExternalsPlugin.ts | 11 -- .../HttpExternalsRspackPlugin.ts | 11 ++ .../src/builtin-plugin/NodeTargetPlugin.ts | 4 +- .../src/builtin-plugin/ProgressPlugin.ts | 10 +- .../src/builtin-plugin/ProvidePlugin.ts | 4 +- .../builtin-plugin/SwcCssMinimizerPlugin.ts | 6 +- .../builtin-plugin/SwcJsMinimizerPlugin.ts | 36 ++-- packages/rspack/src/builtin-plugin/base.ts | 34 ++-- packages/rspack/src/builtin-plugin/index.ts | 46 ++--- packages/rspack/src/index.ts | 14 +- packages/rspack/src/rspackOptionsApply.ts | 7 - packages/rspack/tests/Stats.test.ts | 4 +- .../tests/__snapshots__/Stats.test.ts.snap | 4 +- .../__snapshots__/StatsTestCases.test.ts.snap | 32 ++-- .../watch/_t2/directory/tempfile1.txt | 1 - .../watch/_t2/directory/tempfile2.txt | 1 - 50 files changed, 545 insertions(+), 539 deletions(-) delete mode 100644 packages/rspack/src/builtin-plugin/CopyPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/CopyRspackPlugin.ts rename packages/rspack/src/builtin-plugin/{HtmlPlugin.ts => HtmlRspackPlugin.ts} (69%) delete mode 100644 packages/rspack/src/builtin-plugin/HttpExternalsPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts delete mode 100644 packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile1.txt delete mode 100644 packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile2.txt diff --git a/Cargo.lock b/Cargo.lock index bd3f79ace16..d8b06351c84 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2441,7 +2441,6 @@ dependencies = [ "derivative", "dyn-clone", "futures", - "glob", "glob-match", "hashlink", "indexmap 1.9.3", diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index 12b701a0f3b..1f972a69bb3 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -110,24 +110,24 @@ export interface BeforeResolveData { } export interface BuiltinPlugin { - kind: BuiltinPluginKind + name: BuiltinPluginName options: unknown } -export const enum BuiltinPluginKind { - Define = 'Define', - Provide = 'Provide', - Banner = 'Banner', - Progress = 'Progress', - Copy = 'Copy', - Html = 'Html', - SwcJsMinimizer = 'SwcJsMinimizer', - SwcCssMinimizer = 'SwcCssMinimizer', - Entry = 'Entry', - Externals = 'Externals', - NodeTarget = 'NodeTarget', - ElectronTarget = 'ElectronTarget', - HttpExternals = 'HttpExternals' +export const enum BuiltinPluginName { + DefinePlugin = 'DefinePlugin', + ProvidePlugin = 'ProvidePlugin', + BannerPlugin = 'BannerPlugin', + ProgressPlugin = 'ProgressPlugin', + EntryPlugin = 'EntryPlugin', + ExternalsPlugin = 'ExternalsPlugin', + NodeTargetPlugin = 'NodeTargetPlugin', + ElectronTargetPlugin = 'ElectronTargetPlugin', + HttpExternalsRspackPlugin = 'HttpExternalsRspackPlugin', + CopyRspackPlugin = 'CopyRspackPlugin', + HtmlRspackPlugin = 'HtmlRspackPlugin', + SwcJsMinimizerRspackPlugin = 'SwcJsMinimizerRspackPlugin', + SwcCssMinimizerRspackPlugin = 'SwcCssMinimizerRspackPlugin' } export function cleanupGlobalTrace(): void @@ -492,39 +492,39 @@ export interface RawAssetResourceGeneratorOptions { publicPath?: string } -export interface RawBannerCondition { - type: "string" | "regexp" - stringMatcher?: string - regexpMatcher?: string +export interface RawBannerContent { + type: "string" | "function" + stringPayload?: string + fnPayload?: (...args: any[]) => any } -export interface RawBannerConditions { - type: "string" | "regexp" | "array" - stringMatcher?: string - regexpMatcher?: string - arrayMatcher?: Array +export interface RawBannerContentFnCtx { + hash: string + chunk: JsChunk + filename: string } -export interface RawBannerConfig { +export interface RawBannerPluginOptions { banner: RawBannerContent entryOnly?: boolean footer?: boolean raw?: boolean - test?: RawBannerConditions - include?: RawBannerConditions - exclude?: RawBannerConditions + test?: RawBannerRules + include?: RawBannerRules + exclude?: RawBannerRules } -export interface RawBannerContent { - type: "string" | "function" - stringPayload?: string - fnPayload?: (...args: any[]) => any +export interface RawBannerRule { + type: "string" | "regexp" + stringMatcher?: string + regexpMatcher?: string } -export interface RawBannerContentFnCtx { - hash: string - chunk: JsChunk - filename: string +export interface RawBannerRules { + type: "string" | "regexp" | "array" + stringMatcher?: string + regexpMatcher?: string + arrayMatcher?: Array } export interface RawBuiltins { @@ -569,8 +569,25 @@ export interface RawCacheOptions { version: string } -export interface RawCopyConfig { - patterns: Array +export interface RawCopyGlobOptions { + caseSensitiveMatch?: boolean + dot?: boolean + ignore?: Array +} + +export interface RawCopyPattern { + from: string + to?: string + context?: string + toType?: string + noErrorOnMissing: boolean + force: boolean + priority: number + globOptions: RawCopyGlobOptions +} + +export interface RawCopyRspackPluginOptions { + patterns: Array } export interface RawCrossOriginLoading { @@ -685,13 +702,7 @@ export interface RawGeneratorOptions { assetResource?: RawAssetResourceGeneratorOptions } -export interface RawGlobOptions { - caseSensitiveMatch?: boolean - dot?: boolean - ignore?: Array -} - -export interface RawHtmlPluginConfig { +export interface RawHtmlRspackPluginOptions { /** emitted file name in output path */ filename?: string /** template html file */ @@ -714,7 +725,7 @@ export interface RawHtmlPluginConfig { meta?: Record> } -export interface RawHttpExternalsPluginOptions { +export interface RawHttpExternalsRspackPluginOptions { css: boolean } @@ -744,33 +755,6 @@ export interface RawLibraryOptions { auxiliaryComment?: RawLibraryAuxiliaryComment } -export interface RawMinification { - passes: number - dropConsole: boolean - keepClassNames: boolean - keepFnNames: boolean - comments: "all" | "some" | "false" - asciiOnly: boolean - pureFuncs: Array - extractComments?: string - test?: RawMinificationConditions - include?: RawMinificationConditions - exclude?: RawMinificationConditions -} - -export interface RawMinificationCondition { - type: "string" | "regexp" - stringMatcher?: string - regexpMatcher?: string -} - -export interface RawMinificationConditions { - type: "string" | "regexp" | "array" - stringMatcher?: string - regexpMatcher?: string - arrayMatcher?: Array -} - export interface RawModuleOptions { rules: Array parser?: Record @@ -911,17 +895,6 @@ export interface RawParserOptions { asset?: RawAssetParserOptions } -export interface RawPattern { - from: string - to?: string - context?: string - toType?: string - noErrorOnMissing: boolean - force: boolean - priority: number - globOptions: RawGlobOptions -} - export interface RawPluginImportConfig { libraryName: string libraryDirectory?: string @@ -940,7 +913,7 @@ export interface RawPresetEnv { coreJs?: string } -export interface RawProgressPluginConfig { +export interface RawProgressPluginOptions { prefix?: string } @@ -1036,6 +1009,33 @@ export interface RawStyleConfig { bool?: boolean } +export interface RawSwcJsMinimizerRspackPluginOptions { + passes: number + dropConsole: boolean + keepClassNames: boolean + keepFnNames: boolean + comments: "all" | "some" | "false" + asciiOnly: boolean + pureFuncs: Array + extractComments?: string + test?: RawSwcJsMinimizerRules + include?: RawSwcJsMinimizerRules + exclude?: RawSwcJsMinimizerRules +} + +export interface RawSwcJsMinimizerRule { + type: "string" | "regexp" + stringMatcher?: string + regexpMatcher?: string +} + +export interface RawSwcJsMinimizerRules { + type: "string" | "regexp" | "array" + stringMatcher?: string + regexpMatcher?: string + arrayMatcher?: Array +} + export interface RawTrustedTypes { policyName?: string } diff --git a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs index 47005a64ff2..7c7ab2f6e04 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs @@ -10,51 +10,54 @@ use napi::{ JsUnknown, }; use napi_derive::napi; -use rspack_core::{ - BoxPlugin, CopyPluginConfig, Define, DefinePlugin, PluginExt, Provide, ProvidePlugin, -}; +use rspack_core::{BoxPlugin, Define, DefinePlugin, PluginExt, Provide, ProvidePlugin}; use rspack_error::Result; use rspack_napi_shared::NapiResultExt; use rspack_plugin_banner::BannerPlugin; -use rspack_plugin_copy::CopyPlugin; +use rspack_plugin_copy::{CopyRspackPlugin, CopyRspackPluginOptions}; use rspack_plugin_entry::EntryPlugin; use rspack_plugin_externals::{ - electron_target_plugin, http_externals_plugin, node_target_plugin, ExternalsPlugin, + electron_target_plugin, http_externals_rspack_plugin, node_target_plugin, ExternalsPlugin, }; -use rspack_plugin_html::HtmlPlugin; +use rspack_plugin_html::HtmlRspackPlugin; use rspack_plugin_progress::ProgressPlugin; -use rspack_plugin_swc_css_minimizer::SwcCssMinimizerPlugin; -use rspack_plugin_swc_js_minimizer::SwcJsMinimizerPlugin; +use rspack_plugin_swc_css_minimizer::SwcCssMinimizerRspackPlugin; +use rspack_plugin_swc_js_minimizer::SwcJsMinimizerRspackPlugin; pub use self::{ - raw_banner::RawBannerConfig, raw_copy::RawCopyConfig, raw_html::RawHtmlPluginConfig, - raw_progress::RawProgressPluginConfig, raw_swc_js_minimizer::RawMinification, + raw_banner::RawBannerPluginOptions, raw_copy::RawCopyRspackPluginOptions, + raw_html::RawHtmlRspackPluginOptions, raw_progress::RawProgressPluginOptions, + raw_swc_js_minimizer::RawSwcJsMinimizerRspackPluginOptions, }; use crate::{ - RawEntryPluginOptions, RawExternalsPluginOptions, RawHttpExternalsPluginOptions, RawOptionsApply, + RawEntryPluginOptions, RawExternalsPluginOptions, RawHttpExternalsRspackPluginOptions, + RawOptionsApply, }; #[napi(string_enum)] #[derive(Debug)] -pub enum BuiltinPluginKind { - Define, - Provide, - Banner, - Progress, - Copy, - Html, - SwcJsMinimizer, - SwcCssMinimizer, - Entry, - Externals, - NodeTarget, - ElectronTarget, - HttpExternals, +pub enum BuiltinPluginName { + // webpack also have these plugins + DefinePlugin, + ProvidePlugin, + BannerPlugin, + ProgressPlugin, + EntryPlugin, + ExternalsPlugin, + NodeTargetPlugin, + ElectronTargetPlugin, + + // rspack specific plugins + HttpExternalsRspackPlugin, + CopyRspackPlugin, + HtmlRspackPlugin, + SwcJsMinimizerRspackPlugin, + SwcCssMinimizerRspackPlugin, } #[napi(object)] pub struct BuiltinPlugin { - pub kind: BuiltinPluginKind, + pub name: BuiltinPluginName, pub options: JsUnknown, } @@ -65,46 +68,28 @@ impl RawOptionsApply for BuiltinPlugin { self, plugins: &mut Vec, ) -> std::result::Result { - match self.kind { - BuiltinPluginKind::Define => { + match self.name { + BuiltinPluginName::DefinePlugin => { let plugin = DefinePlugin::new(downcast_into::(self.options)?).boxed(); plugins.push(plugin); } - BuiltinPluginKind::Provide => { + BuiltinPluginName::ProvidePlugin => { let plugin = ProvidePlugin::new(downcast_into::(self.options)?).boxed(); plugins.push(plugin); } - BuiltinPluginKind::Banner => { + BuiltinPluginName::BannerPlugin => { let plugin = - BannerPlugin::new(downcast_into::(self.options)?.try_into()?).boxed(); - plugins.push(plugin); - } - BuiltinPluginKind::SwcJsMinimizer => { - let plugin = - SwcJsMinimizerPlugin::new(downcast_into::(self.options)?.try_into()?) + BannerPlugin::new(downcast_into::(self.options)?.try_into()?) .boxed(); plugins.push(plugin); } - BuiltinPluginKind::SwcCssMinimizer => plugins.push(SwcCssMinimizerPlugin {}.boxed()), - BuiltinPluginKind::Progress => { + BuiltinPluginName::ProgressPlugin => { let plugin = - ProgressPlugin::new(downcast_into::(self.options)?.into()) + ProgressPlugin::new(downcast_into::(self.options)?.into()) .boxed(); plugins.push(plugin); } - BuiltinPluginKind::Copy => { - let plugin = CopyPlugin::new( - CopyPluginConfig::from(downcast_into::(self.options)?).patterns, - ) - .boxed(); - plugins.push(plugin); - } - BuiltinPluginKind::Html => { - let plugin = - HtmlPlugin::new(downcast_into::(self.options)?.into()).boxed(); - plugins.push(plugin); - } - BuiltinPluginKind::Entry => { + BuiltinPluginName::EntryPlugin => { let plugin_options = downcast_into::(self.options)?; let context = plugin_options.context.into(); let entry_request = plugin_options.entry; @@ -112,7 +97,7 @@ impl RawOptionsApply for BuiltinPlugin { let plugin = EntryPlugin::new(context, entry_request, options).boxed(); plugins.push(plugin); } - BuiltinPluginKind::Externals => { + BuiltinPluginName::ExternalsPlugin => { let plugin_options = downcast_into::(self.options)?; let externals = plugin_options .externals @@ -122,14 +107,38 @@ impl RawOptionsApply for BuiltinPlugin { let plugin = ExternalsPlugin::new(plugin_options.r#type, externals).boxed(); plugins.push(plugin); } - BuiltinPluginKind::NodeTarget => plugins.push(node_target_plugin()), - BuiltinPluginKind::ElectronTarget => { + BuiltinPluginName::NodeTargetPlugin => plugins.push(node_target_plugin()), + BuiltinPluginName::ElectronTargetPlugin => { let context = downcast_into::(self.options)?; electron_target_plugin(context.into(), plugins) } - BuiltinPluginKind::HttpExternals => { - let plugin_options = downcast_into::(self.options)?; - let plugin = http_externals_plugin(plugin_options.css); + BuiltinPluginName::HttpExternalsRspackPlugin => { + let plugin_options = downcast_into::(self.options)?; + let plugin = http_externals_rspack_plugin(plugin_options.css); + plugins.push(plugin); + } + BuiltinPluginName::SwcJsMinimizerRspackPlugin => { + let plugin = SwcJsMinimizerRspackPlugin::new( + downcast_into::(self.options)?.try_into()?, + ) + .boxed(); + plugins.push(plugin); + } + BuiltinPluginName::SwcCssMinimizerRspackPlugin => { + plugins.push(SwcCssMinimizerRspackPlugin {}.boxed()) + } + BuiltinPluginName::CopyRspackPlugin => { + let plugin = CopyRspackPlugin::new( + CopyRspackPluginOptions::from(downcast_into::(self.options)?) + .patterns, + ) + .boxed(); + plugins.push(plugin); + } + BuiltinPluginName::HtmlRspackPlugin => { + let plugin = + HtmlRspackPlugin::new(downcast_into::(self.options)?.into()) + .boxed(); plugins.push(plugin); } } diff --git a/crates/rspack_binding_options/src/options/raw_builtins/raw_banner.rs b/crates/rspack_binding_options/src/options/raw_builtins/raw_banner.rs index 88bdfd82a2a..5767c5cb949 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/raw_banner.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/raw_banner.rs @@ -9,7 +9,7 @@ use rspack_napi_shared::{ NapiResultExt, NAPI_ENV, }; use rspack_plugin_banner::{ - BannerCondition, BannerConditions, BannerConfig, BannerContent, BannerContentFnCtx, + BannerContent, BannerContentFnCtx, BannerPluginOptions, BannerRule, BannerRules, }; use serde::Deserialize; @@ -18,7 +18,7 @@ use crate::chunk::JsChunk; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawBannerCondition { +pub struct RawBannerRule { #[napi(ts_type = r#""string" | "regexp""#)] pub r#type: String, pub string_matcher: Option, @@ -28,12 +28,12 @@ pub struct RawBannerCondition { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawBannerConditions { +pub struct RawBannerRules { #[napi(ts_type = r#""string" | "regexp" | "array""#)] pub r#type: String, pub string_matcher: Option, pub regexp_matcher: Option, - pub array_matcher: Option>, + pub array_matcher: Option>, } #[napi(object)] @@ -109,20 +109,20 @@ impl TryFrom for BannerContent { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawBannerConfig { +pub struct RawBannerPluginOptions { pub banner: RawBannerContent, pub entry_only: Option, pub footer: Option, pub raw: Option, - pub test: Option, - pub include: Option, - pub exclude: Option, + pub test: Option, + pub include: Option, + pub exclude: Option, } -impl TryFrom for BannerCondition { +impl TryFrom for BannerRule { type Error = rspack_error::Error; - fn try_from(x: RawBannerCondition) -> rspack_error::Result { + fn try_from(x: RawBannerRule) -> rspack_error::Result { let result = match x.r#type.as_str() { "string" => Self::String(x.string_matcher.ok_or_else(|| { internal_error!("should have a string_matcher when BannerConditions.type is \"string\"") @@ -144,11 +144,11 @@ impl TryFrom for BannerCondition { } } -impl TryFrom for BannerConditions { +impl TryFrom for BannerRules { type Error = rspack_error::Error; - fn try_from(x: RawBannerConditions) -> rspack_error::Result { - let result: BannerConditions = match x.r#type.as_str() { + fn try_from(x: RawBannerRules) -> rspack_error::Result { + let result: BannerRules = match x.r#type.as_str() { "string" => Self::String(x.string_matcher.ok_or_else(|| { internal_error!("should have a string_matcher when BannerConditions.type is \"string\"") })?), @@ -180,14 +180,14 @@ impl TryFrom for BannerConditions { } } -impl TryFrom for BannerConfig { +impl TryFrom for BannerPluginOptions { type Error = rspack_error::Error; - fn try_from(value: RawBannerConfig) -> std::result::Result { + fn try_from(value: RawBannerPluginOptions) -> std::result::Result { fn try_condition( - raw_condition: Option, - ) -> Result, rspack_error::Error> { - let condition: Option = if let Some(test) = raw_condition { + raw_condition: Option, + ) -> Result, rspack_error::Error> { + let condition: Option = if let Some(test) = raw_condition { Some(test.try_into()?) } else { None @@ -196,7 +196,7 @@ impl TryFrom for BannerConfig { Ok(condition) } - Ok(BannerConfig { + Ok(BannerPluginOptions { banner: value.banner.try_into()?, entry_only: value.entry_only, footer: value.footer, diff --git a/crates/rspack_binding_options/src/options/raw_builtins/raw_copy.rs b/crates/rspack_binding_options/src/options/raw_builtins/raw_copy.rs index af050483e24..2f077d72367 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/raw_copy.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/raw_copy.rs @@ -1,13 +1,13 @@ use std::path::PathBuf; use napi_derive::napi; -use rspack_core::{CopyPluginConfig, GlobOptions, Pattern, ToType}; +use rspack_plugin_copy::{CopyGlobOptions, CopyPattern, CopyRspackPluginOptions, ToType}; use serde::Deserialize; #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawPattern { +pub struct RawCopyPattern { pub from: String, pub to: Option, pub context: Option, @@ -15,13 +15,13 @@ pub struct RawPattern { pub no_error_on_missing: bool, pub force: bool, pub priority: i32, - pub glob_options: RawGlobOptions, + pub glob_options: RawCopyGlobOptions, } #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawGlobOptions { +pub struct RawCopyGlobOptions { pub case_sensitive_match: Option, pub dot: Option, pub ignore: Option>, @@ -30,13 +30,13 @@ pub struct RawGlobOptions { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawCopyConfig { - pub patterns: Vec, +pub struct RawCopyRspackPluginOptions { + pub patterns: Vec, } -impl From for Pattern { - fn from(value: RawPattern) -> Self { - let RawPattern { +impl From for CopyPattern { + fn from(value: RawCopyPattern) -> Self { + let RawCopyPattern { from, to, context, @@ -68,7 +68,7 @@ impl From for Pattern { info: None, force, priority, - glob_options: GlobOptions { + glob_options: CopyGlobOptions { case_sensitive_match: glob_options.case_sensitive_match, dot: glob_options.dot, ignore: glob_options.ignore.map(|ignore| { @@ -82,8 +82,8 @@ impl From for Pattern { } } -impl From for CopyPluginConfig { - fn from(val: RawCopyConfig) -> Self { +impl From for CopyRspackPluginOptions { + fn from(val: RawCopyRspackPluginOptions) -> Self { Self { patterns: val.patterns.into_iter().map(Into::into).collect(), } diff --git a/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs b/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs index 12d216207bd..9c2d4319869 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs @@ -2,22 +2,22 @@ use std::collections::HashMap; use std::str::FromStr; use napi_derive::napi; -use rspack_plugin_html::config::HtmlPluginConfig; -use rspack_plugin_html::config::HtmlPluginConfigInject; -use rspack_plugin_html::config::HtmlPluginConfigScriptLoading; +use rspack_plugin_html::config::HtmlInject; +use rspack_plugin_html::config::HtmlRspackPluginOptions; +use rspack_plugin_html::config::HtmlScriptLoading; use rspack_plugin_html::sri::HtmlSriHashFunction; use serde::Deserialize; use serde::Serialize; -pub type RawHtmlPluginConfigScriptLoading = String; -pub type RawHtmlPluginConfigInject = String; +pub type RawHtmlScriptLoading = String; +pub type RawHtmlInject = String; pub type RawHtmlSriHashFunction = String; pub type RawHtmlFilename = String; #[derive(Deserialize, Debug, Serialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawHtmlPluginConfig { +pub struct RawHtmlRspackPluginOptions { /// emitted file name in output path #[napi(ts_type = "string")] pub filename: Option, @@ -27,12 +27,12 @@ pub struct RawHtmlPluginConfig { pub template_parameters: Option>, /// `head`, `body` or None #[napi(ts_type = "\"head\" | \"body\"")] - pub inject: Option, + pub inject: Option, /// path or `auto` pub public_path: Option, /// `blocking`, `defer`, or `module` #[napi(ts_type = "\"blocking\" | \"defer\" | \"module\"")] - pub script_loading: Option, + pub script_loading: Option, /// entry_chunk_name (only entry chunks are supported) pub chunks: Option>, @@ -45,13 +45,14 @@ pub struct RawHtmlPluginConfig { pub meta: Option>>, } -impl From for HtmlPluginConfig { - fn from(value: RawHtmlPluginConfig) -> Self { - let inject = value.inject.as_ref().map(|s| { - HtmlPluginConfigInject::from_str(s).unwrap_or_else(|_| panic!("Invalid inject value: {s}")) - }); +impl From for HtmlRspackPluginOptions { + fn from(value: RawHtmlRspackPluginOptions) -> Self { + let inject = value + .inject + .as_ref() + .map(|s| HtmlInject::from_str(s).unwrap_or_else(|_| panic!("Invalid inject value: {s}"))); - let script_loading = HtmlPluginConfigScriptLoading::from_str( + let script_loading = HtmlScriptLoading::from_str( &value .script_loading .unwrap_or_else(|| String::from("defer")), @@ -62,7 +63,7 @@ impl From for HtmlPluginConfig { HtmlSriHashFunction::from_str(s).unwrap_or_else(|_| panic!("Invalid sri value: {s}")) }); - HtmlPluginConfig { + HtmlRspackPluginOptions { filename: value.filename.unwrap_or_else(|| String::from("index.html")), template: value.template, template_content: value.template_content, diff --git a/crates/rspack_binding_options/src/options/raw_builtins/raw_progress.rs b/crates/rspack_binding_options/src/options/raw_builtins/raw_progress.rs index b263d8a920b..e8585fef0f3 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/raw_progress.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/raw_progress.rs @@ -1,16 +1,16 @@ use napi_derive::napi; -use rspack_plugin_progress::ProgressPluginConfig; +use rspack_plugin_progress::ProgressPluginOptions; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Debug, Serialize, Clone)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawProgressPluginConfig { +pub struct RawProgressPluginOptions { pub prefix: Option, } -impl From for ProgressPluginConfig { - fn from(value: RawProgressPluginConfig) -> Self { +impl From for ProgressPluginOptions { + fn from(value: RawProgressPluginOptions) -> Self { Self { prefix: value.prefix, } diff --git a/crates/rspack_binding_options/src/options/raw_builtins/raw_swc_js_minimizer.rs b/crates/rspack_binding_options/src/options/raw_builtins/raw_swc_js_minimizer.rs index f834e6aeb80..6b93a97bdc4 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/raw_swc_js_minimizer.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/raw_swc_js_minimizer.rs @@ -1,12 +1,14 @@ use napi_derive::napi; use rspack_error::internal_error; -use rspack_plugin_swc_js_minimizer::{Minification, MinificationCondition, MinificationConditions}; +use rspack_plugin_swc_js_minimizer::{ + SwcJsMinimizerRspackPluginOptions, SwcJsMinimizerRule, SwcJsMinimizerRules, +}; use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawMinificationCondition { +pub struct RawSwcJsMinimizerRule { #[napi(ts_type = r#""string" | "regexp""#)] pub r#type: String, pub string_matcher: Option, @@ -16,18 +18,18 @@ pub struct RawMinificationCondition { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawMinificationConditions { +pub struct RawSwcJsMinimizerRules { #[napi(ts_type = r#""string" | "regexp" | "array""#)] pub r#type: String, pub string_matcher: Option, pub regexp_matcher: Option, - pub array_matcher: Option>, + pub array_matcher: Option>, } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawMinification { +pub struct RawSwcJsMinimizerRspackPluginOptions { pub passes: u32, pub drop_console: bool, pub keep_class_names: bool, @@ -37,19 +39,19 @@ pub struct RawMinification { pub ascii_only: bool, pub pure_funcs: Vec, pub extract_comments: Option, - pub test: Option, - pub include: Option, - pub exclude: Option, + pub test: Option, + pub include: Option, + pub exclude: Option, } -impl TryFrom for Minification { +impl TryFrom for SwcJsMinimizerRspackPluginOptions { type Error = rspack_error::Error; - fn try_from(value: RawMinification) -> rspack_error::Result { + fn try_from(value: RawSwcJsMinimizerRspackPluginOptions) -> rspack_error::Result { fn try_condition( - raw_condition: Option, - ) -> Result, rspack_error::Error> { - let condition: Option = if let Some(test) = raw_condition { + raw_condition: Option, + ) -> Result, rspack_error::Error> { + let condition: Option = if let Some(test) = raw_condition { Some(test.try_into()?) } else { None @@ -74,10 +76,10 @@ impl TryFrom for Minification { } } -impl TryFrom for MinificationCondition { +impl TryFrom for SwcJsMinimizerRule { type Error = rspack_error::Error; - fn try_from(x: RawMinificationCondition) -> rspack_error::Result { + fn try_from(x: RawSwcJsMinimizerRule) -> rspack_error::Result { let result = match x.r#type.as_str() { "string" => Self::String(x.string_matcher.ok_or_else(|| { internal_error!( @@ -101,11 +103,11 @@ impl TryFrom for MinificationCondition { } } -impl TryFrom for MinificationConditions { +impl TryFrom for SwcJsMinimizerRules { type Error = rspack_error::Error; - fn try_from(value: RawMinificationConditions) -> rspack_error::Result { - let result: MinificationConditions = match value.r#type.as_str() { + fn try_from(value: RawSwcJsMinimizerRules) -> rspack_error::Result { + let result = match value.r#type.as_str() { "string" => Self::String(value.string_matcher.ok_or_else(|| { internal_error!("should have a string_matcher when MinificationConditions.type is \"string\"") })?), diff --git a/crates/rspack_binding_options/src/options/raw_external.rs b/crates/rspack_binding_options/src/options/raw_external.rs index 5d2e5af36b3..06c6a0fced8 100644 --- a/crates/rspack_binding_options/src/options/raw_external.rs +++ b/crates/rspack_binding_options/src/options/raw_external.rs @@ -19,7 +19,7 @@ use { #[derive(Deserialize)] #[serde(rename_all = "camelCase")] #[napi(object)] -pub struct RawHttpExternalsPluginOptions { +pub struct RawHttpExternalsRspackPluginOptions { pub css: bool, } diff --git a/crates/rspack_core/Cargo.toml b/crates/rspack_core/Cargo.toml index 4ca90bfb2a2..c90513d58d1 100644 --- a/crates/rspack_core/Cargo.toml +++ b/crates/rspack_core/Cargo.toml @@ -15,7 +15,6 @@ dashmap = { workspace = true } derivative = { workspace = true } dyn-clone = "1.0.11" futures = { workspace = true } -glob = "0.3.1" glob-match = "0.2.1" hashlink = { workspace = true } indexmap = { workspace = true } diff --git a/crates/rspack_core/src/options/builtins.rs b/crates/rspack_core/src/options/builtins.rs index 3dada906cdf..d9364558895 100644 --- a/crates/rspack_core/src/options/builtins.rs +++ b/crates/rspack_core/src/options/builtins.rs @@ -1,12 +1,10 @@ use std::fmt::Debug; -use std::{fmt::Display, path::PathBuf}; -use glob::Pattern as GlobPattern; use rspack_error::Result; pub use rspack_swc_visitors::{Define, Provide}; use rspack_swc_visitors::{EmotionOptions, ImportOptions, ReactOptions, RelayOptions}; -use crate::{ApplyContext, AssetInfo, CompilerOptions, Plugin, PluginContext}; +use crate::{ApplyContext, CompilerOptions, Plugin, PluginContext}; #[derive(Debug)] pub struct DefinePlugin { @@ -141,54 +139,6 @@ pub struct Builtins { pub relay: Option, } -#[derive(Debug, Clone)] -pub struct CopyPluginConfig { - pub patterns: Vec, -} - -#[derive(Debug, Clone, Copy)] -pub enum FromType { - Dir, - File, - Glob, -} - -#[derive(Debug, Clone)] -pub enum ToType { - Dir, - File, - Template, -} - -impl Display for ToType { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(match self { - ToType::Dir => "dir", - ToType::File => "file", - ToType::Template => "template", - }) - } -} - -#[derive(Debug, Clone)] -pub struct Pattern { - pub from: String, - pub to: Option, - pub context: Option, - pub to_type: Option, - pub no_error_on_missing: bool, - pub info: Option, - pub force: bool, - pub priority: i32, - pub glob_options: GlobOptions, -} - -#[derive(Debug, Clone)] -pub struct GlobOptions { - pub case_sensitive_match: Option, - pub dot: Option, - pub ignore: Option>, -} #[derive(Debug, Clone, Default)] pub struct PresetEnv { pub targets: Vec, diff --git a/crates/rspack_plugin_banner/src/lib.rs b/crates/rspack_plugin_banner/src/lib.rs index 9a252480e92..a96ced341f4 100644 --- a/crates/rspack_plugin_banner/src/lib.rs +++ b/crates/rspack_plugin_banner/src/lib.rs @@ -16,19 +16,19 @@ use rspack_regex::RspackRegex; use rspack_util::try_any; #[derive(Debug)] -pub enum BannerCondition { +pub enum BannerRule { String(String), Regexp(RspackRegex), } #[derive(Debug)] -pub enum BannerConditions { +pub enum BannerRules { String(String), Regexp(RspackRegex), - Array(Vec), + Array(Vec), } -impl BannerCondition { +impl BannerRule { #[async_recursion] pub async fn try_match(&self, data: &str) -> Result { match self { @@ -38,7 +38,7 @@ impl BannerCondition { } } -impl BannerConditions { +impl BannerRules { #[async_recursion] pub async fn try_match(&self, data: &str) -> Result { match self { @@ -50,7 +50,7 @@ impl BannerConditions { } #[derive(Debug)] -pub struct BannerConfig { +pub struct BannerPluginOptions { // Specifies the banner. pub banner: BannerContent, // If true, the banner will only be added to the entry chunks. @@ -60,11 +60,11 @@ pub struct BannerConfig { // If true, banner will not be wrapped in a comment. pub raw: Option, // Include all modules that pass test assertion. - pub test: Option, + pub test: Option, // Include all modules matching any of these conditions. - pub include: Option, + pub include: Option, // Exclude all modules matching any of these conditions. - pub exclude: Option, + pub exclude: Option, } pub struct BannerContentFnCtx<'a> { @@ -91,7 +91,7 @@ impl fmt::Debug for BannerContent { } #[async_recursion] -async fn match_object(obj: &BannerConfig, str: &str) -> Result { +async fn match_object(obj: &BannerPluginOptions, str: &str) -> Result { if let Some(condition) = &obj.test { if !condition.try_match(str).await? { return Ok(false); @@ -131,11 +131,11 @@ fn wrap_comment(str: &str) -> String { #[derive(Debug)] pub struct BannerPlugin { - config: BannerConfig, + config: BannerPluginOptions, } impl BannerPlugin { - pub fn new(config: BannerConfig) -> Self { + pub fn new(config: BannerPluginOptions) -> Self { Self { config } } diff --git a/crates/rspack_plugin_copy/src/lib.rs b/crates/rspack_plugin_copy/src/lib.rs index 72efb818acf..d9cf89c59ec 100644 --- a/crates/rspack_plugin_copy/src/lib.rs +++ b/crates/rspack_plugin_copy/src/lib.rs @@ -1,5 +1,6 @@ #![feature(let_chains)] use std::{ + fmt::Display, fs, hash::Hash, path::{Path, PathBuf, MAIN_SEPARATOR}, @@ -8,16 +9,65 @@ use std::{ use async_trait::async_trait; use dashmap::DashSet; -use glob::MatchOptions; +use glob::{MatchOptions, Pattern as GlobPattern}; use regex::Regex; use rspack_core::{ rspack_sources::RawSource, AssetInfo, Compilation, CompilationAsset, CompilationLogger, Filename, - FromType, Logger, PathData, Pattern, Plugin, ToType, + Logger, PathData, Plugin, }; use rspack_error::Diagnostic; use rspack_hash::{HashDigest, HashFunction, HashSalt, RspackHash, RspackHashDigest}; use sugar_path::{AsPath, SugarPath}; +#[derive(Debug, Clone)] +pub struct CopyRspackPluginOptions { + pub patterns: Vec, +} + +#[derive(Debug, Clone, Copy)] +pub enum FromType { + Dir, + File, + Glob, +} + +#[derive(Debug, Clone)] +pub enum ToType { + Dir, + File, + Template, +} + +impl Display for ToType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + ToType::Dir => "dir", + ToType::File => "file", + ToType::Template => "template", + }) + } +} + +#[derive(Debug, Clone)] +pub struct CopyPattern { + pub from: String, + pub to: Option, + pub context: Option, + pub to_type: Option, + pub no_error_on_missing: bool, + pub info: Option, + pub force: bool, + pub priority: i32, + pub glob_options: CopyGlobOptions, +} + +#[derive(Debug, Clone)] +pub struct CopyGlobOptions { + pub case_sensitive_match: Option, + pub dot: Option, + pub ignore: Option>, +} + #[derive(Debug, Clone)] pub struct RunPatternResult { pub source_filename: PathBuf, @@ -30,8 +80,8 @@ pub struct RunPatternResult { } #[derive(Debug)] -pub struct CopyPlugin { - pub patterns: Vec, +pub struct CopyRspackPlugin { + pub patterns: Vec, } lazy_static::lazy_static! { @@ -39,8 +89,8 @@ lazy_static::lazy_static! { static ref TEMPLATE_RE: Regex = Regex::new(r"\[\\*([\w:]+)\\*\]").expect("This never fail"); } -impl CopyPlugin { - pub fn new(patterns: Vec) -> Self { +impl CopyRspackPlugin { + pub fn new(patterns: Vec) -> Self { Self { patterns } } @@ -65,7 +115,7 @@ impl CopyPlugin { #[allow(clippy::too_many_arguments)] async fn analyze_every_entry( entry: PathBuf, - pattern: &Pattern, + pattern: &CopyPattern, context: &Path, output_path: &Path, from_type: FromType, @@ -216,7 +266,7 @@ impl CopyPlugin { fn run_patter( compilation: &Compilation, - pattern: &Pattern, + pattern: &CopyPattern, _index: usize, file_dependencies: &DashSet, context_dependencies: &DashSet, @@ -432,9 +482,9 @@ impl CopyPlugin { } #[async_trait] -impl Plugin for CopyPlugin { +impl Plugin for CopyRspackPlugin { fn name(&self) -> &'static str { - "rspack.CopyPlugin" + "rspack.CopyRspackPlugin" } async fn process_assets_stage_additional( diff --git a/crates/rspack_plugin_externals/src/http_externals_plugin.rs b/crates/rspack_plugin_externals/src/http_externals_plugin.rs index ff864bd71a2..e84c95529d7 100644 --- a/crates/rspack_plugin_externals/src/http_externals_plugin.rs +++ b/crates/rspack_plugin_externals/src/http_externals_plugin.rs @@ -13,7 +13,7 @@ static EXTERNAL_HTTP_STD_REQUEST: Lazy = static EXTERNAL_CSS_REQUEST: Lazy = Lazy::new(|| Regex::new(r"^\.css(\?|$)").expect("Invalid regex")); -pub fn http_externals_plugin(css: bool) -> BoxPlugin { +pub fn http_externals_rspack_plugin(css: bool) -> BoxPlugin { ExternalsPlugin::new("module".to_owned(), vec![http_external_item(css)]).boxed() } diff --git a/crates/rspack_plugin_externals/src/lib.rs b/crates/rspack_plugin_externals/src/lib.rs index 5d840981986..f5881ea19f0 100644 --- a/crates/rspack_plugin_externals/src/lib.rs +++ b/crates/rspack_plugin_externals/src/lib.rs @@ -6,6 +6,6 @@ mod node_target_plugin; mod plugin; pub use electron_target_plugin::{electron_target_plugin, ElectronTargetContext}; -pub use http_externals_plugin::http_externals_plugin; +pub use http_externals_plugin::http_externals_rspack_plugin; pub use node_target_plugin::node_target_plugin; pub use plugin::ExternalsPlugin; diff --git a/crates/rspack_plugin_html/src/config.rs b/crates/rspack_plugin_html/src/config.rs index 87a9b725673..1a0fcac121d 100644 --- a/crates/rspack_plugin_html/src/config.rs +++ b/crates/rspack_plugin_html/src/config.rs @@ -11,19 +11,19 @@ use crate::sri::HtmlSriHashFunction; #[cfg_attr(feature = "testing", derive(JsonSchema))] #[derive(Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] -pub enum HtmlPluginConfigInject { +pub enum HtmlInject { Head, Body, } -impl FromStr for HtmlPluginConfigInject { +impl FromStr for HtmlInject { type Err = anyhow::Error; fn from_str(s: &str) -> Result { if s.eq("head") { - Ok(HtmlPluginConfigInject::Head) + Ok(HtmlInject::Head) } else if s.eq("body") { - Ok(HtmlPluginConfigInject::Body) + Ok(HtmlInject::Body) } else { Err(anyhow::Error::msg( "inject in html config only support 'head' or 'body'", @@ -35,22 +35,22 @@ impl FromStr for HtmlPluginConfigInject { #[cfg_attr(feature = "testing", derive(JsonSchema))] #[derive(Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "snake_case")] -pub enum HtmlPluginConfigScriptLoading { +pub enum HtmlScriptLoading { Blocking, Defer, Module, } -impl FromStr for HtmlPluginConfigScriptLoading { +impl FromStr for HtmlScriptLoading { type Err = anyhow::Error; fn from_str(s: &str) -> Result { if s.eq("blocking") { - Ok(HtmlPluginConfigScriptLoading::Blocking) + Ok(HtmlScriptLoading::Blocking) } else if s.eq("defer") { - Ok(HtmlPluginConfigScriptLoading::Defer) + Ok(HtmlScriptLoading::Defer) } else if s.eq("module") { - Ok(HtmlPluginConfigScriptLoading::Module) + Ok(HtmlScriptLoading::Module) } else { Err(anyhow::Error::msg( "scriptLoading in html config only support 'blocking', 'defer' or 'module'", @@ -62,7 +62,7 @@ impl FromStr for HtmlPluginConfigScriptLoading { #[cfg_attr(feature = "testing", derive(JsonSchema))] #[derive(Deserialize, Debug)] #[serde(rename_all = "camelCase", deny_unknown_fields)] -pub struct HtmlPluginConfig { +pub struct HtmlRspackPluginOptions { /// emitted file name in output path #[serde(default = "default_filename")] pub filename: String, @@ -71,12 +71,12 @@ pub struct HtmlPluginConfig { pub template_content: Option, pub template_parameters: Option>, /// `head`, `body` or None - pub inject: Option, + pub inject: Option, /// path or `auto` pub public_path: Option, /// `blocking`, `defer`, or `module` #[serde(default = "default_script_loading")] - pub script_loading: HtmlPluginConfigScriptLoading, + pub script_loading: HtmlScriptLoading, /// entry_chunk_name (only entry chunks are supported) pub chunks: Option>, @@ -96,13 +96,13 @@ fn default_filename() -> String { String::from("index.html") } -fn default_script_loading() -> HtmlPluginConfigScriptLoading { - HtmlPluginConfigScriptLoading::Defer +fn default_script_loading() -> HtmlScriptLoading { + HtmlScriptLoading::Defer } -impl Default for HtmlPluginConfig { - fn default() -> HtmlPluginConfig { - HtmlPluginConfig { +impl Default for HtmlRspackPluginOptions { + fn default() -> HtmlRspackPluginOptions { + HtmlRspackPluginOptions { filename: default_filename(), template: None, template_content: None, @@ -121,7 +121,7 @@ impl Default for HtmlPluginConfig { } } -impl HtmlPluginConfig { +impl HtmlRspackPluginOptions { pub fn get_public_path(&self, compilation: &Compilation, filename: &str) -> String { match &self.public_path { Some(p) => PublicPath::ensure_ends_with_slash(p.clone()), diff --git a/crates/rspack_plugin_html/src/parser.rs b/crates/rspack_plugin_html/src/parser.rs index 7b7d7df3d18..3be6f2586a7 100644 --- a/crates/rspack_plugin_html/src/parser.rs +++ b/crates/rspack_plugin_html/src/parser.rs @@ -14,14 +14,14 @@ use swc_html::{ use swc_html_minifier::minify_document; pub use swc_html_minifier::option::MinifyOptions; -use crate::config::HtmlPluginConfig; +use crate::config::HtmlRspackPluginOptions; pub struct HtmlCompiler<'a> { - config: &'a HtmlPluginConfig, + config: &'a HtmlRspackPluginOptions, } impl<'a> HtmlCompiler<'a> { - pub fn new(config: &'a HtmlPluginConfig) -> Self { + pub fn new(config: &'a HtmlRspackPluginOptions) -> Self { Self { config } } diff --git a/crates/rspack_plugin_html/src/plugin.rs b/crates/rspack_plugin_html/src/plugin.rs index c3f755e8551..d6868a6c5e4 100644 --- a/crates/rspack_plugin_html/src/plugin.rs +++ b/crates/rspack_plugin_html/src/plugin.rs @@ -18,20 +18,20 @@ use serde::Deserialize; use swc_html::visit::VisitMutWith; use crate::{ - config::{HtmlPluginConfig, HtmlPluginConfigInject}, + config::{HtmlInject, HtmlRspackPluginOptions}, parser::HtmlCompiler, sri::{add_sri, create_digest_from_asset}, visitors::asset::{AssetWriter, HTMLPluginTag}, }; #[derive(Deserialize, Debug, Default)] -pub struct HtmlPlugin { - config: HtmlPluginConfig, +pub struct HtmlRspackPlugin { + config: HtmlRspackPluginOptions, } -impl HtmlPlugin { - pub fn new(config: HtmlPluginConfig) -> HtmlPlugin { - HtmlPlugin { config } +impl HtmlRspackPlugin { + pub fn new(config: HtmlRspackPluginOptions) -> HtmlRspackPlugin { + HtmlRspackPlugin { config } } } fn default_template() -> &'static str { @@ -47,9 +47,9 @@ fn default_template() -> &'static str { } #[async_trait] -impl Plugin for HtmlPlugin { +impl Plugin for HtmlRspackPlugin { fn name(&self) -> &'static str { - "html" + "rspack.HtmlRspackPlugin" } async fn process_assets_stage_optimize_inline( @@ -145,7 +145,7 @@ impl Plugin for HtmlPlugin { Some(if let Some(inject) = &config.inject { *inject } else { - HtmlPluginConfigInject::Head + HtmlInject::Head }), )); } else if extension.eq_ignore_ascii_case("js") || extension.eq_ignore_ascii_case("mjs") { @@ -154,7 +154,7 @@ impl Plugin for HtmlPlugin { Some(if let Some(inject) = &config.inject { *inject } else { - HtmlPluginConfigInject::Head + HtmlInject::Head }), &config.script_loading, )) diff --git a/crates/rspack_plugin_html/src/visitors/asset.rs b/crates/rspack_plugin_html/src/visitors/asset.rs index 5bbe5585bc4..0cd90fe5169 100644 --- a/crates/rspack_plugin_html/src/visitors/asset.rs +++ b/crates/rspack_plugin_html/src/visitors/asset.rs @@ -9,7 +9,7 @@ use swc_html::ast::{Attribute, Child, Element, Namespace, Text}; use swc_html::visit::{VisitMut, VisitMutWith}; use super::utils::create_element; -use crate::config::{HtmlPluginConfig, HtmlPluginConfigInject, HtmlPluginConfigScriptLoading}; +use crate::config::{HtmlInject, HtmlRspackPluginOptions, HtmlScriptLoading}; // the tag #[derive(Debug)] @@ -18,14 +18,14 @@ pub struct HTMLPluginTag { pub attributes: Vec, pub void_tag: bool, // `head` or `body` - pub append_to: HtmlPluginConfigInject, + pub append_to: HtmlInject, } impl HTMLPluginTag { - pub fn create_style(href: &str, append_to: Option) -> HTMLPluginTag { + pub fn create_style(href: &str, append_to: Option) -> HTMLPluginTag { HTMLPluginTag { tag_name: "link".to_string(), - append_to: append_to.unwrap_or(HtmlPluginConfigInject::Head), + append_to: append_to.unwrap_or(HtmlInject::Head), attributes: vec![ HtmlPluginAttribute { attr_name: "href".to_string(), @@ -42,21 +42,21 @@ impl HTMLPluginTag { pub fn create_script( src: &str, - append_to: Option, - script_loading: &HtmlPluginConfigScriptLoading, + append_to: Option, + script_loading: &HtmlScriptLoading, ) -> HTMLPluginTag { let mut attributes = vec![HtmlPluginAttribute { attr_name: "src".to_string(), attr_value: Some(src.to_string()), }]; match script_loading { - HtmlPluginConfigScriptLoading::Defer => { + HtmlScriptLoading::Defer => { attributes.push(HtmlPluginAttribute { attr_name: "defer".to_string(), attr_value: None, }); } - HtmlPluginConfigScriptLoading::Module => { + HtmlScriptLoading::Module => { attributes.push(HtmlPluginAttribute { attr_name: "type".to_string(), attr_value: Some("module".to_string()), @@ -67,7 +67,7 @@ impl HTMLPluginTag { HTMLPluginTag { tag_name: "script".to_string(), - append_to: append_to.unwrap_or(HtmlPluginConfigInject::Body), + append_to: append_to.unwrap_or(HtmlInject::Body), attributes, void_tag: false, } @@ -85,7 +85,7 @@ pub struct HtmlPluginAttribute { #[derive(Debug)] pub struct AssetWriter<'a, 'c> { - config: &'a HtmlPluginConfig, + config: &'a HtmlRspackPluginOptions, head_tags: Vec<&'a HTMLPluginTag>, body_tags: Vec<&'a HTMLPluginTag>, compilation: &'c Compilation, @@ -93,7 +93,7 @@ pub struct AssetWriter<'a, 'c> { impl<'a, 'c> AssetWriter<'a, 'c> { pub fn new( - config: &'a HtmlPluginConfig, + config: &'a HtmlRspackPluginOptions, tags: &'a [HTMLPluginTag], compilation: &'c Compilation, ) -> AssetWriter<'a, 'c> { @@ -101,10 +101,10 @@ impl<'a, 'c> AssetWriter<'a, 'c> { let mut body_tags: Vec<&HTMLPluginTag> = vec![]; for ele in tags.iter() { match ele.append_to { - HtmlPluginConfigInject::Head => { + HtmlInject::Head => { head_tags.push(ele); } - HtmlPluginConfigInject::Body => { + HtmlInject::Body => { body_tags.push(ele); } } diff --git a/crates/rspack_plugin_progress/src/lib.rs b/crates/rspack_plugin_progress/src/lib.rs index 1e1439653ee..42070542bab 100644 --- a/crates/rspack_plugin_progress/src/lib.rs +++ b/crates/rspack_plugin_progress/src/lib.rs @@ -11,14 +11,14 @@ use rspack_core::{ use rspack_error::Result; #[derive(Debug, Clone, Default)] -pub struct ProgressPluginConfig { +pub struct ProgressPluginOptions { // the prefix name of progress bar pub prefix: Option, } #[derive(Debug)] pub struct ProgressPlugin { - pub options: ProgressPluginConfig, + pub options: ProgressPluginOptions, pub progress_bar: ProgressBar, pub modules_count: AtomicU32, pub modules_done: AtomicU32, @@ -26,7 +26,7 @@ pub struct ProgressPlugin { } impl ProgressPlugin { - pub fn new(options: ProgressPluginConfig) -> Self { + pub fn new(options: ProgressPluginOptions) -> Self { let progress_bar = ProgressBar::with_draw_target(Some(100), ProgressDrawTarget::stdout()); progress_bar.set_style( ProgressStyle::with_template("{prefix} {bar:40.cyan/blue} {percent}% {wide_msg}") diff --git a/crates/rspack_plugin_swc_css_minimizer/src/lib.rs b/crates/rspack_plugin_swc_css_minimizer/src/lib.rs index 8c9cb077260..126b7c90e17 100644 --- a/crates/rspack_plugin_swc_css_minimizer/src/lib.rs +++ b/crates/rspack_plugin_swc_css_minimizer/src/lib.rs @@ -5,12 +5,12 @@ use rspack_error::Result; use rspack_plugin_css::swc_css_compiler::{SwcCssCompiler, SwcCssSourceMapGenConfig}; #[derive(Debug)] -pub struct SwcCssMinimizerPlugin; +pub struct SwcCssMinimizerRspackPlugin; #[async_trait] -impl Plugin for SwcCssMinimizerPlugin { +impl Plugin for SwcCssMinimizerRspackPlugin { fn name(&self) -> &'static str { - "rspack.SwcCssMinimizerPlugin" + "rspack.SwcCssMinimizerRspackPlugin" } // TODO: chunk hash diff --git a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs index ea3bda313ce..eb3af0d26f8 100644 --- a/crates/rspack_plugin_swc_js_minimizer/src/lib.rs +++ b/crates/rspack_plugin_swc_js_minimizer/src/lib.rs @@ -26,7 +26,7 @@ use swc_ecma_minifier::option::{ }; #[derive(Debug, Clone, Default, Hash)] -pub struct Minification { +pub struct SwcJsMinimizerRspackPluginOptions { pub passes: usize, pub drop_console: bool, pub keep_class_names: bool, @@ -35,18 +35,18 @@ pub struct Minification { pub extract_comments: Option, pub ascii_only: bool, pub comments: String, - pub test: Option, - pub include: Option, - pub exclude: Option, + pub test: Option, + pub include: Option, + pub exclude: Option, } #[derive(Debug, Clone, Hash)] -pub enum MinificationCondition { +pub enum SwcJsMinimizerRule { String(String), Regexp(RspackRegex), } -impl MinificationCondition { +impl SwcJsMinimizerRule { #[async_recursion] pub async fn try_match(&self, data: &str) -> rspack_error::Result { match self { @@ -57,13 +57,13 @@ impl MinificationCondition { } #[derive(Debug, Clone, Hash)] -pub enum MinificationConditions { +pub enum SwcJsMinimizerRules { String(String), Regexp(rspack_regex::RspackRegex), - Array(Vec), + Array(Vec), } -impl MinificationConditions { +impl SwcJsMinimizerRules { #[async_recursion] pub async fn try_match(&self, data: &str) -> rspack_error::Result { match self { @@ -75,20 +75,20 @@ impl MinificationConditions { } #[derive(Debug)] -pub struct SwcJsMinimizerPlugin { - options: Minification, +pub struct SwcJsMinimizerRspackPlugin { + options: SwcJsMinimizerRspackPluginOptions, } -impl SwcJsMinimizerPlugin { - pub fn new(options: Minification) -> Self { +impl SwcJsMinimizerRspackPlugin { + pub fn new(options: SwcJsMinimizerRspackPluginOptions) -> Self { Self { options } } } #[async_trait] -impl Plugin for SwcJsMinimizerPlugin { +impl Plugin for SwcJsMinimizerRspackPlugin { fn name(&self) -> &'static str { - "rspack.SwcJsMinimizerPlugin" + "rspack.SwcJsMinimizerRspackPlugin" } async fn process_assets_stage_optimize_size( diff --git a/crates/rspack_plugin_swc_js_minimizer/src/minify.rs b/crates/rspack_plugin_swc_js_minimizer/src/minify.rs index f948be4dc27..0f39e9f6e08 100644 --- a/crates/rspack_plugin_swc_js_minimizer/src/minify.rs +++ b/crates/rspack_plugin_swc_js_minimizer/src/minify.rs @@ -41,10 +41,10 @@ use swc_ecma_minifier::{ option::{MinifyOptions, TopLevelOptions}, }; -use crate::{JsMinifyCommentOption, JsMinifyOptions, Minification}; +use crate::{JsMinifyCommentOption, JsMinifyOptions, SwcJsMinimizerRspackPluginOptions}; #[async_recursion] -pub async fn match_object(obj: &Minification, str: &str) -> Result { +pub async fn match_object(obj: &SwcJsMinimizerRspackPluginOptions, str: &str) -> Result { if let Some(condition) = &obj.test { if !condition.try_match(str).await? { return Ok(false); diff --git a/crates/rspack_testing/src/test_config.rs b/crates/rspack_testing/src/test_config.rs index 0c997701ea3..cc2720fe73f 100644 --- a/crates/rspack_testing/src/test_config.rs +++ b/crates/rspack_testing/src/test_config.rs @@ -6,7 +6,7 @@ use std::{ }; use rspack_core::{BoxPlugin, CompilerOptions, ModuleType, PluginExt}; -use rspack_plugin_html::config::HtmlPluginConfig; +use rspack_plugin_html::config::HtmlRspackPluginOptions; use rspack_regex::RspackRegex; use schemars::JsonSchema; use serde::Deserialize; @@ -168,7 +168,7 @@ pub struct Builtins { #[serde(default)] pub provide: HashMap>, #[serde(default)] - pub html: Vec, + pub html: Vec, #[serde(default)] pub minify_options: Option, #[serde(default = "default_tree_shaking")] @@ -465,7 +465,7 @@ impl TestConfig { .push(rspack_plugin_dev_friendly_split_chunks::DevFriendlySplitChunksPlugin::new().boxed()); } for html in self.builtins.html { - plugins.push(rspack_plugin_html::HtmlPlugin::new(html).boxed()); + plugins.push(rspack_plugin_html::HtmlRspackPlugin::new(html).boxed()); } plugins.push( rspack_plugin_css::CssPlugin::new(rspack_plugin_css::plugin::CssConfig { @@ -549,7 +549,7 @@ impl TestConfig { plugins.push(rspack_plugin_wasm::FetchCompileAsyncWasmPlugin {}.boxed()); plugins.push(rspack_plugin_wasm::AsyncWasmPlugin::new().boxed()); } - plugins.push(rspack_plugin_externals::http_externals_plugin(true)); + plugins.push(rspack_plugin_externals::http_externals_rspack_plugin(true)); // Support resolving builtin loaders on the Native side plugins.push(crate::loader::BuiltinLoaderResolver.boxed()); diff --git a/packages/rspack-dev-server/tests/normalizeOptions.test.ts b/packages/rspack-dev-server/tests/normalizeOptions.test.ts index 7951141955d..0cf778fdb96 100644 --- a/packages/rspack-dev-server/tests/normalizeOptions.test.ts +++ b/packages/rspack-dev-server/tests/normalizeOptions.test.ts @@ -123,9 +123,8 @@ async function matchAdditionEntries( const server = new RspackDevServer(serverConfig, compiler); await server.start(); const entries = compiler.builtinPlugins - .map(p => p.raw()) - .filter(p => p.kind === "Entry" /* BuiltinPluginKind.Entry */) - .map(p => p.options) + .filter(p => p.name === "EntryPlugin") + .map(p => p.raw().options) .reduce((acc, cur: any) => { const name = cur.options.name; const request = cur.entry; diff --git a/packages/rspack/src/Compiler.ts b/packages/rspack/src/Compiler.ts index 06eab2a2c1e..84e9ebdf3c0 100644 --- a/packages/rspack/src/Compiler.ts +++ b/packages/rspack/src/Compiler.ts @@ -44,7 +44,7 @@ import { normalizeJsModule } from "./util/normalization"; import { ElectronTargetPlugin, ExternalsPlugin, - HttpExternalsPlugin, + HttpExternalsRspackPlugin, NodeTargetPlugin, RspackBuiltinPlugin, deprecated_resolveBuiltins @@ -341,7 +341,7 @@ class Compiler { options.externalsPresets.web || (options.externalsPresets.node && options.experiments.css) ) { - new HttpExternalsPlugin(!!options.experiments.css).apply(this); + new HttpExternalsRspackPlugin(!!options.experiments.css).apply(this); } EntryOptionPlugin.applyEntryOption(this, this.context, options.entry); } diff --git a/packages/rspack/src/builtin-plugin/BannerPlugin.ts b/packages/rspack/src/builtin-plugin/BannerPlugin.ts index efe3deb332d..0e46bdd6589 100644 --- a/packages/rspack/src/builtin-plugin/BannerPlugin.ts +++ b/packages/rspack/src/builtin-plugin/BannerPlugin.ts @@ -1,12 +1,12 @@ import { z } from "zod"; import { JsChunk, - RawBannerCondition, - RawBannerConditions, - RawBannerConfig, - RawBannerContent + RawBannerContent, + RawBannerPluginOptions, + RawBannerRule, + RawBannerRules } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; const rule = z.string().or(z.instanceof(RegExp)); export type Rule = z.infer; @@ -43,7 +43,7 @@ export type BannerPluginOptions = z.infer; const bannerPluginArgument = bannerContent.or(bannerPluginOptions); export type BannerPluginArgument = z.infer; -function getRawBannerRule(condition: Rule): RawBannerCondition { +function getRawBannerRule(condition: Rule): RawBannerRule { if (typeof condition === "string") { return { type: "string", @@ -59,7 +59,7 @@ function getRawBannerRule(condition: Rule): RawBannerCondition { throw new Error("unreachable: condition should be one of string, RegExp"); } -function getRawBannerRules(condition?: Rules): RawBannerConditions | undefined { +function getRawBannerRules(condition?: Rules): RawBannerRules | undefined { if (!condition) return undefined; if (Array.isArray(condition)) { @@ -89,8 +89,8 @@ function getRawBannerContent(content: BannerContent): RawBannerContent { } export const BannerPlugin = create( - BuiltinPluginKind.Banner, - (args: BannerPluginArgument): RawBannerConfig => { + BuiltinPluginName.BannerPlugin, + (args: BannerPluginArgument): RawBannerPluginOptions => { if (typeof args === "string") { return { banner: getRawBannerContent(args) diff --git a/packages/rspack/src/builtin-plugin/CopyPlugin.ts b/packages/rspack/src/builtin-plugin/CopyPlugin.ts deleted file mode 100644 index e56c3b6e7be..00000000000 --- a/packages/rspack/src/builtin-plugin/CopyPlugin.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { RawCopyConfig, RawPattern } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; - -export type CopyPluginOptions = { - patterns: ( - | string - | ({ - from: string; - } & Partial) - )[]; -}; - -export const CopyPlugin = create( - BuiltinPluginKind.Copy, - (copy: CopyPluginOptions): RawCopyConfig => { - const ret: RawCopyConfig = { - patterns: [] - }; - - ret.patterns = (copy.patterns || []).map(pattern => { - if (typeof pattern === "string") { - pattern = { from: pattern }; - } - - pattern.force ??= false; - pattern.noErrorOnMissing ??= false; - pattern.priority ??= 0; - pattern.globOptions ??= {}; - - return pattern as RawPattern; - }); - - return ret; - } -); diff --git a/packages/rspack/src/builtin-plugin/CopyRspackPlugin.ts b/packages/rspack/src/builtin-plugin/CopyRspackPlugin.ts new file mode 100644 index 00000000000..49713227f16 --- /dev/null +++ b/packages/rspack/src/builtin-plugin/CopyRspackPlugin.ts @@ -0,0 +1,35 @@ +import { RawCopyPattern, RawCopyRspackPluginOptions } from "@rspack/binding"; +import { BuiltinPluginName, create } from "./base"; + +export type CopyRspackPluginOptions = { + patterns: ( + | string + | ({ + from: string; + } & Partial) + )[]; +}; + +export const CopyRspackPlugin = create( + BuiltinPluginName.CopyRspackPlugin, + (copy: CopyRspackPluginOptions): RawCopyRspackPluginOptions => { + const ret: RawCopyRspackPluginOptions = { + patterns: [] + }; + + ret.patterns = (copy.patterns || []).map(pattern => { + if (typeof pattern === "string") { + pattern = { from: pattern }; + } + + pattern.force ??= false; + pattern.noErrorOnMissing ??= false; + pattern.priority ??= 0; + pattern.globOptions ??= {}; + + return pattern as RawCopyPattern; + }); + + return ret; + } +); diff --git a/packages/rspack/src/builtin-plugin/DefinePlugin.ts b/packages/rspack/src/builtin-plugin/DefinePlugin.ts index d1f0215f69c..f1ba1734928 100644 --- a/packages/rspack/src/builtin-plugin/DefinePlugin.ts +++ b/packages/rspack/src/builtin-plugin/DefinePlugin.ts @@ -1,8 +1,8 @@ -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; export type DefinePluginOptions = Record; export const DefinePlugin = create( - BuiltinPluginKind.Define, + BuiltinPluginName.DefinePlugin, (define: DefinePluginOptions): Record => { const entries = Object.entries(define).map(([key, value]) => { if (typeof value !== "string") { diff --git a/packages/rspack/src/builtin-plugin/ElectronTargetPlugin.ts b/packages/rspack/src/builtin-plugin/ElectronTargetPlugin.ts index ccf766992c2..bbb004be6e6 100644 --- a/packages/rspack/src/builtin-plugin/ElectronTargetPlugin.ts +++ b/packages/rspack/src/builtin-plugin/ElectronTargetPlugin.ts @@ -1,6 +1,6 @@ -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; export const ElectronTargetPlugin = create( - BuiltinPluginKind.ElectronTarget, + BuiltinPluginName.ElectronTargetPlugin, (context?: string) => context ?? "none" ); diff --git a/packages/rspack/src/builtin-plugin/EntryPlugin.ts b/packages/rspack/src/builtin-plugin/EntryPlugin.ts index 2449a1923a8..41cfd6388d0 100644 --- a/packages/rspack/src/builtin-plugin/EntryPlugin.ts +++ b/packages/rspack/src/builtin-plugin/EntryPlugin.ts @@ -1,5 +1,5 @@ import { RawEntryOptions, RawEntryPluginOptions } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; import { ChunkLoading, EntryRuntime, Filename, PublicPath } from ".."; export type EntryOptions = { @@ -12,7 +12,7 @@ export type EntryOptions = { filename?: Filename; }; export const EntryPlugin = create( - BuiltinPluginKind.Entry, + BuiltinPluginName.EntryPlugin, ( context: string, entry: string, diff --git a/packages/rspack/src/builtin-plugin/ExternalsPlugin.ts b/packages/rspack/src/builtin-plugin/ExternalsPlugin.ts index e40fdd03dd6..a401e883a51 100644 --- a/packages/rspack/src/builtin-plugin/ExternalsPlugin.ts +++ b/packages/rspack/src/builtin-plugin/ExternalsPlugin.ts @@ -3,11 +3,11 @@ import { RawExternalItemValue, RawExternalsPluginOptions } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; import { ExternalItem, ExternalItemValue, Externals } from ".."; export const ExternalsPlugin = create( - BuiltinPluginKind.Externals, + BuiltinPluginName.ExternalsPlugin, (type: string, externals: Externals): RawExternalsPluginOptions => { return { type, diff --git a/packages/rspack/src/builtin-plugin/HtmlPlugin.ts b/packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts similarity index 69% rename from packages/rspack/src/builtin-plugin/HtmlPlugin.ts rename to packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts index 0a4f4471b68..4a8bf1f9543 100644 --- a/packages/rspack/src/builtin-plugin/HtmlPlugin.ts +++ b/packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts @@ -1,9 +1,9 @@ import { z } from "zod"; -import { RawHtmlPluginConfig } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; +import { RawHtmlRspackPluginOptions } from "@rspack/binding"; +import { BuiltinPluginName, create } from "./base"; import { validate } from "../util/validate"; -const htmlPluginOptions = z.strictObject({ +const htmlRspackPluginOptions = z.strictObject({ filename: z.string().optional(), template: z.string().optional(), templateContent: z.string().optional(), @@ -19,11 +19,11 @@ const htmlPluginOptions = z.strictObject({ favicon: z.string().optional(), meta: z.record(z.string().or(z.record(z.string()))).optional() }); -export type HtmlPluginOptions = z.infer; -export const HtmlPlugin = create( - BuiltinPluginKind.Html, - (c: HtmlPluginOptions): RawHtmlPluginConfig => { - validate(c, htmlPluginOptions); +export type HtmlRspackPluginOptions = z.infer; +export const HtmlRspackPlugin = create( + BuiltinPluginName.HtmlRspackPlugin, + (c: HtmlRspackPluginOptions): RawHtmlRspackPluginOptions => { + validate(c, htmlRspackPluginOptions); const meta: Record> = {}; for (const key in c.meta) { const value = c.meta[key]; diff --git a/packages/rspack/src/builtin-plugin/HttpExternalsPlugin.ts b/packages/rspack/src/builtin-plugin/HttpExternalsPlugin.ts deleted file mode 100644 index c77eeaadd4c..00000000000 --- a/packages/rspack/src/builtin-plugin/HttpExternalsPlugin.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { RawHttpExternalsPluginOptions } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; - -export const HttpExternalsPlugin = create( - BuiltinPluginKind.HttpExternals, - (css: boolean): RawHttpExternalsPluginOptions => { - return { - css - }; - } -); diff --git a/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts b/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts new file mode 100644 index 00000000000..3d4cbecd7c0 --- /dev/null +++ b/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts @@ -0,0 +1,11 @@ +import { RawHttpExternalsRspackPluginOptions } from "@rspack/binding"; +import { BuiltinPluginName, create } from "./base"; + +export const HttpExternalsRspackPlugin = create( + BuiltinPluginName.HttpExternalsRspackPlugin, + (css: boolean): RawHttpExternalsRspackPluginOptions => { + return { + css + }; + } +); diff --git a/packages/rspack/src/builtin-plugin/NodeTargetPlugin.ts b/packages/rspack/src/builtin-plugin/NodeTargetPlugin.ts index 914e11b8685..9277a6ef910 100644 --- a/packages/rspack/src/builtin-plugin/NodeTargetPlugin.ts +++ b/packages/rspack/src/builtin-plugin/NodeTargetPlugin.ts @@ -1,6 +1,6 @@ -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; export const NodeTargetPlugin = create( - BuiltinPluginKind.NodeTarget, + BuiltinPluginName.NodeTargetPlugin, () => undefined ); diff --git a/packages/rspack/src/builtin-plugin/ProgressPlugin.ts b/packages/rspack/src/builtin-plugin/ProgressPlugin.ts index 49b2d8612cd..a7f4beee126 100644 --- a/packages/rspack/src/builtin-plugin/ProgressPlugin.ts +++ b/packages/rspack/src/builtin-plugin/ProgressPlugin.ts @@ -1,8 +1,8 @@ -import { RawProgressPluginConfig } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; +import { RawProgressPluginOptions } from "@rspack/binding"; +import { BuiltinPluginName, create } from "./base"; -export type ProgressPluginArgument = RawProgressPluginConfig | undefined; +export type ProgressPluginArgument = RawProgressPluginOptions | undefined; export const ProgressPlugin = create( - BuiltinPluginKind.Progress, - (progress: ProgressPluginArgument = {}): RawProgressPluginConfig => progress + BuiltinPluginName.ProgressPlugin, + (progress: ProgressPluginArgument = {}): RawProgressPluginOptions => progress ); diff --git a/packages/rspack/src/builtin-plugin/ProvidePlugin.ts b/packages/rspack/src/builtin-plugin/ProvidePlugin.ts index 8b7ef3b0eec..c89fcee25fd 100644 --- a/packages/rspack/src/builtin-plugin/ProvidePlugin.ts +++ b/packages/rspack/src/builtin-plugin/ProvidePlugin.ts @@ -1,8 +1,8 @@ -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; export type ProvidePluginOptions = Record; export const ProvidePlugin = create( - BuiltinPluginKind.Provide, + BuiltinPluginName.ProvidePlugin, (provide: ProvidePluginOptions): Record => { const entries = Object.entries(provide).map(([key, value]) => { if (typeof value === "string") { diff --git a/packages/rspack/src/builtin-plugin/SwcCssMinimizerPlugin.ts b/packages/rspack/src/builtin-plugin/SwcCssMinimizerPlugin.ts index a444a4efbf9..842f4f248bf 100644 --- a/packages/rspack/src/builtin-plugin/SwcCssMinimizerPlugin.ts +++ b/packages/rspack/src/builtin-plugin/SwcCssMinimizerPlugin.ts @@ -1,6 +1,6 @@ -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; -export const SwcCssMinimizerPlugin = create( - BuiltinPluginKind.SwcCssMinimizer, +export const SwcCssMinimizerRspackPlugin = create( + BuiltinPluginName.SwcCssMinimizerRspackPlugin, (options?: any /* TODO: extend more options */) => undefined ); diff --git a/packages/rspack/src/builtin-plugin/SwcJsMinimizerPlugin.ts b/packages/rspack/src/builtin-plugin/SwcJsMinimizerPlugin.ts index f4d5459882e..4233ecc1309 100644 --- a/packages/rspack/src/builtin-plugin/SwcJsMinimizerPlugin.ts +++ b/packages/rspack/src/builtin-plugin/SwcJsMinimizerPlugin.ts @@ -1,13 +1,13 @@ import { - RawMinification, - RawMinificationCondition, - RawMinificationConditions + RawSwcJsMinimizerRspackPluginOptions, + RawSwcJsMinimizerRule, + RawSwcJsMinimizerRules } from "@rspack/binding"; -import { BuiltinPluginKind, create } from "./base"; +import { BuiltinPluginName, create } from "./base"; type MinifyCondition = string | RegExp; type MinifyConditions = MinifyCondition | MinifyCondition[]; -export type SwcJsMinimizerPluginOptions = { +export type SwcJsMinimizerRspackPluginOptions = { passes?: number; dropConsole?: boolean; keepClassNames?: boolean; @@ -21,9 +21,9 @@ export type SwcJsMinimizerPluginOptions = { include?: MinifyConditions; }; -function getMinifyCondition( +function getRawSwcJsMinimizerRule( condition: MinifyCondition -): RawMinificationCondition { +): RawSwcJsMinimizerRule { if (typeof condition === "string") { return { type: "string", @@ -39,24 +39,26 @@ function getMinifyCondition( throw new Error("unreachable: condition should be one of string, RegExp"); } -function getMinifyConditions( +function getRawSwcJsMinimizerRules( condition?: MinifyConditions -): RawMinificationConditions | undefined { +): RawSwcJsMinimizerRules | undefined { if (!condition) return undefined; if (Array.isArray(condition)) { return { type: "array", - arrayMatcher: condition.map(i => getMinifyCondition(i)) + arrayMatcher: condition.map(i => getRawSwcJsMinimizerRule(i)) }; } - return getMinifyCondition(condition); + return getRawSwcJsMinimizerRule(condition); } -export const SwcJsMinimizerPlugin = create( - BuiltinPluginKind.SwcJsMinimizer, - (options?: SwcJsMinimizerPluginOptions): RawMinification => { +export const SwcJsMinimizerRspackPlugin = create( + BuiltinPluginName.SwcJsMinimizerRspackPlugin, + ( + options?: SwcJsMinimizerRspackPluginOptions + ): RawSwcJsMinimizerRspackPluginOptions => { return { passes: options?.passes ?? 1, dropConsole: options?.dropConsole ?? false, @@ -68,9 +70,9 @@ export const SwcJsMinimizerPlugin = create( extractComments: options?.extractComments ? String(options.extractComments) : undefined, - test: getMinifyConditions(options?.test), - include: getMinifyConditions(options?.include), - exclude: getMinifyConditions(options?.exclude) + test: getRawSwcJsMinimizerRules(options?.test), + include: getRawSwcJsMinimizerRules(options?.include), + exclude: getRawSwcJsMinimizerRules(options?.exclude) }; } ); diff --git a/packages/rspack/src/builtin-plugin/base.ts b/packages/rspack/src/builtin-plugin/base.ts index cef64202d50..4e79e457f4a 100644 --- a/packages/rspack/src/builtin-plugin/base.ts +++ b/packages/rspack/src/builtin-plugin/base.ts @@ -2,34 +2,36 @@ import * as binding from "@rspack/binding"; import { Compiler, RspackPluginInstance } from ".."; // TODO: workaround for https://github.com/napi-rs/napi-rs/pull/1690 -export enum BuiltinPluginKind { - Define = "Define", - Provide = "Provide", - Banner = "Banner", - Progress = "Progress", - Copy = "Copy", - Html = "Html", - SwcJsMinimizer = "SwcJsMinimizer", - SwcCssMinimizer = "SwcCssMinimizer", - Entry = "Entry", - Externals = "Externals", - NodeTarget = "NodeTarget", - ElectronTarget = "ElectronTarget", - HttpExternals = "HttpExternals" +export enum BuiltinPluginName { + DefinePlugin = "DefinePlugin", + ProvidePlugin = "ProvidePlugin", + BannerPlugin = "BannerPlugin", + ProgressPlugin = "ProgressPlugin", + EntryPlugin = "EntryPlugin", + ExternalsPlugin = "ExternalsPlugin", + NodeTargetPlugin = "NodeTargetPlugin", + ElectronTargetPlugin = "ElectronTargetPlugin", + HttpExternalsRspackPlugin = "HttpExternalsRspackPlugin", + CopyRspackPlugin = "CopyRspackPlugin", + HtmlRspackPlugin = "HtmlRspackPlugin", + SwcJsMinimizerRspackPlugin = "SwcJsMinimizerRspackPlugin", + SwcCssMinimizerRspackPlugin = "SwcCssMinimizerRspackPlugin" } export abstract class RspackBuiltinPlugin implements RspackPluginInstance { abstract raw(): binding.BuiltinPlugin; + abstract name: BuiltinPluginName; apply(compiler: Compiler) { compiler.__internal__registerBuiltinPlugin(this); } } export function create( - kind: BuiltinPluginKind, + name: BuiltinPluginName, resolve: (...args: T) => R ) { return class Plugin extends RspackBuiltinPlugin { + name = name; _options: R; constructor(...args: T) { @@ -41,7 +43,7 @@ export function create( raw(): binding.BuiltinPlugin { return { - kind: kind as any, + name: name as any, options: this._options }; } diff --git a/packages/rspack/src/builtin-plugin/index.ts b/packages/rspack/src/builtin-plugin/index.ts index 2d3a43d7a90..3cc0b6b8e97 100644 --- a/packages/rspack/src/builtin-plugin/index.ts +++ b/packages/rspack/src/builtin-plugin/index.ts @@ -8,10 +8,10 @@ export * from "./EntryPlugin"; export * from "./ExternalsPlugin"; export * from "./NodeTargetPlugin"; export * from "./ElectronTargetPlugin"; -export * from "./HttpExternalsPlugin"; +export * from "./HttpExternalsRspackPlugin"; -export * from "./HtmlPlugin"; -export * from "./CopyPlugin"; +export * from "./HtmlRspackPlugin"; +export * from "./CopyRspackPlugin"; export * from "./SwcJsMinimizerPlugin"; export * from "./SwcCssMinimizerPlugin"; @@ -19,26 +19,28 @@ export * from "./SwcCssMinimizerPlugin"; import { RawDecoratorOptions, RawPresetEnv, - RawProgressPluginConfig, + RawProgressPluginOptions, RawBuiltins, RawCssModulesConfig } from "@rspack/binding"; import { termlink, deprecatedWarn } from "../util"; -import { Compiler, RspackOptionsNormalized } from ".."; import { - HtmlPluginOptions, - SwcJsMinimizerPluginOptions, - CopyPluginOptions, + Compiler, + CopyRspackPlugin, + CopyRspackPluginOptions, + HtmlRspackPlugin, + HtmlRspackPluginOptions, + RspackOptionsNormalized, + SwcCssMinimizerRspackPlugin, + SwcJsMinimizerRspackPlugin, + SwcJsMinimizerRspackPluginOptions +} from ".."; +import { BannerPluginOptions, DefinePlugin, ProvidePlugin, ProgressPlugin, - HtmlPlugin, - CopyPlugin, - BannerPlugin, - SwcJsMinimizerPlugin, - SwcCssMinimizerPlugin, - RspackBuiltinPlugin + BannerPlugin } from "."; import { loadConfig } from "browserslist"; import { @@ -132,16 +134,16 @@ function resolveDecorator( export interface Builtins { css?: BuiltinsCssConfig; treeShaking?: boolean | "module"; - progress?: boolean | RawProgressPluginConfig; + progress?: boolean | RawProgressPluginOptions; noEmitAssets?: boolean; define?: Record; provide?: Record; - html?: Array; + html?: Array; decorator?: boolean | Partial; - minifyOptions?: SwcJsMinimizerPluginOptions; + minifyOptions?: SwcJsMinimizerRspackPluginOptions; presetEnv?: Partial; devFriendlySplitChunks?: boolean; - copy?: CopyPluginOptions; + copy?: CopyRspackPluginOptions; banner?: BannerPluginOptions | BannerPluginOptions[]; react?: ReactOptions; pluginImport?: PluginImportOptions; @@ -219,7 +221,7 @@ export function deprecated_resolveBuiltins( enableDeprecatedWarning ); for (const html of builtins.html) { - new HtmlPlugin(html).apply(compiler); + new HtmlRspackPlugin(html).apply(compiler); } } if (builtins.copy) { @@ -229,7 +231,7 @@ export function deprecated_resolveBuiltins( )}' has been deprecated, please migrate to rspack.CopyPlugin`, enableDeprecatedWarning ); - new CopyPlugin(builtins.copy).apply(compiler); + new CopyRspackPlugin(builtins.copy).apply(compiler); } if (builtins.minifyOptions) { deprecatedWarn( @@ -243,8 +245,8 @@ export function deprecated_resolveBuiltins( !options.optimization.minimize || options.optimization.minimizer!.some(item => item !== "..."); if (!disableMinify) { - new SwcJsMinimizerPlugin(builtins.minifyOptions).apply(compiler); - new SwcCssMinimizerPlugin().apply(compiler); + new SwcJsMinimizerRspackPlugin(builtins.minifyOptions).apply(compiler); + new SwcCssMinimizerRspackPlugin().apply(compiler); } let noEmitAssets = false; diff --git a/packages/rspack/src/index.ts b/packages/rspack/src/index.ts index b4ec6762100..892044d1906 100644 --- a/packages/rspack/src/index.ts +++ b/packages/rspack/src/index.ts @@ -26,10 +26,10 @@ export { DefinePlugin, ProvidePlugin, ProgressPlugin, - HtmlPlugin, - SwcJsMinimizerPlugin, - SwcCssMinimizerPlugin, - CopyPlugin, + HtmlRspackPlugin, + SwcJsMinimizerRspackPlugin, + SwcCssMinimizerRspackPlugin, + CopyRspackPlugin, EntryPlugin, ExternalsPlugin } from "./builtin-plugin"; @@ -38,9 +38,9 @@ export type { DefinePluginOptions, ProvidePluginOptions, ProgressPluginArgument, - HtmlPluginOptions, - SwcJsMinimizerPluginOptions, - CopyPluginOptions, + HtmlRspackPluginOptions, + SwcJsMinimizerRspackPluginOptions, + CopyRspackPluginOptions, EntryOptions } from "./builtin-plugin"; import { ElectronTargetPlugin, NodeTargetPlugin } from "./builtin-plugin"; diff --git a/packages/rspack/src/rspackOptionsApply.ts b/packages/rspack/src/rspackOptionsApply.ts index 860164cada6..73486506501 100644 --- a/packages/rspack/src/rspackOptionsApply.ts +++ b/packages/rspack/src/rspackOptionsApply.ts @@ -20,14 +20,7 @@ import { DefaultStatsFactoryPlugin } from "./stats/DefaultStatsFactoryPlugin"; import { DefaultStatsPrinterPlugin } from "./stats/DefaultStatsPrinterPlugin"; import { cleverMerge } from "./util/cleverMerge"; import assert from "assert"; -import { - ExternalsPlugin, - HttpExternalsPlugin, - NodeTargetPlugin, - ElectronTargetPlugin -} from "./builtin-plugin"; import IgnoreWarningsPlugin from "./lib/ignoreWarningsPlugin"; -import EntryOptionPlugin from "./lib/EntryOptionPlugin"; export class RspackOptionsApply { constructor() {} diff --git a/packages/rspack/tests/Stats.test.ts b/packages/rspack/tests/Stats.test.ts index dff1a5fd2f5..7b9e671505d 100644 --- a/packages/rspack/tests/Stats.test.ts +++ b/packages/rspack/tests/Stats.test.ts @@ -34,7 +34,7 @@ describe("Stats", () => { entry ./fixtures/a ./fixtures/a.js [876] {main} entry ./fixtures/a - rspack compiled successfully (31124a919605602fc9ae)" + rspack compiled successfully (224575f0bba4bc71b95f)" `); }); @@ -79,7 +79,7 @@ describe("Stats", () => { - rspack compiled with 1 error (18c9b1da202481673984)" + rspack compiled with 1 error (51da9544767033575b9e)" `); }); diff --git a/packages/rspack/tests/__snapshots__/Stats.test.ts.snap b/packages/rspack/tests/__snapshots__/Stats.test.ts.snap index 1f265223833..ec8f4679e40 100644 --- a/packages/rspack/tests/__snapshots__/Stats.test.ts.snap +++ b/packages/rspack/tests/__snapshots__/Stats.test.ts.snap @@ -156,7 +156,7 @@ exports[`Stats should have stats 1`] = ` "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "31124a919605602fc9ae", + "hash": "224575f0bba4bc71b95f", "logging": {}, "modules": [ { @@ -416,7 +416,7 @@ exports.c = require("./c?c=3"); "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "089a36c7767bb55f0574", + "hash": "833faf822e0c01d589e7", "logging": {}, "modules": [ { diff --git a/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap b/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap index d121012c97a..788ecedacb1 100644 --- a/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap +++ b/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap @@ -188,7 +188,7 @@ import rawModule from './raw.png'", "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "94f12aa69d3989830e25", + "hash": "7a935a9f14af6fedd836", "logging": {}, "modules": [ { @@ -337,7 +337,7 @@ chunk {main} bundle.js (main) [entry] entry ./index ./stringModule.js [363] {main} esm import ./stringModule [10] -rspack compiled successfully (94f12aa69d3989830e25)" +rspack compiled successfully (7a935a9f14af6fedd836)" `; exports[`StatsTestCases should print correct stats for filename 1`] = ` @@ -500,7 +500,7 @@ exports[`StatsTestCases should print correct stats for filename 1`] = ` "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "b1dbe683f73e6b1f7f2c", + "hash": "426fdcc9ed1638dfcbc9", "logging": {}, "modules": [ { @@ -602,7 +602,7 @@ chunk {main} main.xxxx.js (main) >{dynamic_js}< [entry] entry ./index ./dynamic.js [426] {dynamic_js} dynamic import ./dynamic [10] -rspack compiled successfully (b1dbe683f73e6b1f7f2c)" +rspack compiled successfully (426fdcc9ed1638dfcbc9)" `; exports[`StatsTestCases should print correct stats for hot+production 1`] = ` @@ -697,7 +697,7 @@ exports[`StatsTestCases should print correct stats for hot+production 1`] = ` "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "86548123ac24bd06a6bf", + "hash": "8b17e56c72949ef15048", "logging": {}, "modules": [ { @@ -760,7 +760,7 @@ chunk {main} bundle.js (main) [entry] entry ./index.js ./index.js [10] {main} entry ./index.js -rspack compiled successfully (86548123ac24bd06a6bf)" +rspack compiled successfully (8b17e56c72949ef15048)" `; exports[`StatsTestCases should print correct stats for identifier-let-strict-mode 1`] = ` @@ -2023,7 +2023,7 @@ console.log(a); ], "errorsCount": 1, "filteredModules": undefined, - "hash": "6ca407f06f94c982125d", + "hash": "745b7086c5177811e94a", "logging": {}, "modules": [ { @@ -2144,7 +2144,7 @@ error[internal]: Resolve error -rspack compiled with 1 error (6ca407f06f94c982125d)" +rspack compiled with 1 error (745b7086c5177811e94a)" `; exports[`StatsTestCases should print correct stats for resolve-unexpected-exports-in-pkg 1`] = ` @@ -2288,7 +2288,7 @@ console.log(a); ], "errorsCount": 1, "filteredModules": undefined, - "hash": "a9093cd411993b4b9c01", + "hash": "4e3ebc05601fcb8c4e16", "logging": {}, "modules": [ { @@ -2403,7 +2403,7 @@ error[internal]: Export should be relative path and start with "./", but got ../ -rspack compiled with 1 error (a9093cd411993b4b9c01)" +rspack compiled with 1 error (4e3ebc05601fcb8c4e16)" `; exports[`StatsTestCases should print correct stats for simple 1`] = ` @@ -2498,7 +2498,7 @@ exports[`StatsTestCases should print correct stats for simple 1`] = ` "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "7a27fed57156f35cc7b2", + "hash": "96a5acbdbd5061c8e5ac", "logging": {}, "modules": [ { @@ -2561,7 +2561,7 @@ chunk {main} bundle.js (main) [entry] entry ./index ./index.js [10] {main} entry ./index -rspack compiled successfully (7a27fed57156f35cc7b2)" +rspack compiled successfully (96a5acbdbd5061c8e5ac)" `; exports[`StatsTestCases should print correct stats for simple-module-source 1`] = ` @@ -2722,7 +2722,7 @@ import rawModule from './raw.png'", "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "ef78d0d53e6750a65525", + "hash": "58ffc7a5ede4848a7209", "logging": {}, "modules": [ { @@ -2849,7 +2849,7 @@ Entrypoint main 631 bytes = bundle.js ./raw.png ./index.js ./stringModule.js -rspack compiled successfully (ef78d0d53e6750a65525)" +rspack compiled successfully (58ffc7a5ede4848a7209)" `; exports[`StatsTestCases should print correct stats for stats-hooks 1`] = ` @@ -2943,7 +2943,7 @@ exports[`StatsTestCases should print correct stats for stats-hooks 1`] = ` "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "7a27fed57156f35cc7b2", + "hash": "96a5acbdbd5061c8e5ac", "logging": {}, "modules": [ { @@ -3000,7 +3000,7 @@ exports[`StatsTestCases should print correct stats for stats-hooks 2`] = ` asset bundle.js 589 bytes [emitted111] (name: main) [testA: aaaaaa] Entrypoint main 589 bytes = bundle.js ./index.js -rspack compiled successfully (7a27fed57156f35cc7b2)" +rspack compiled successfully (96a5acbdbd5061c8e5ac)" `; exports[`StatsTestCases should print correct stats for try-require--module 1`] = ` diff --git a/packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile1.txt b/packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile1.txt deleted file mode 100644 index b3c55476180..00000000000 --- a/packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile1.txt +++ /dev/null @@ -1 +0,0 @@ -file1contents \ No newline at end of file diff --git a/packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile2.txt b/packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile2.txt deleted file mode 100644 index 26ebc2e98bd..00000000000 --- a/packages/rspack/tests/copyPlugin/fixtures/watch/_t2/directory/tempfile2.txt +++ /dev/null @@ -1 +0,0 @@ -file2contents \ No newline at end of file From 254d31daea5b30c8174d6e4cfb8bcc0321fa4b36 Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Mon, 11 Sep 2023 17:04:46 +0800 Subject: [PATCH 06/49] feat(config): warn while using `experiments.newSplitChunks` (#4169) --- packages/rspack/src/config/zod.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/rspack/src/config/zod.ts b/packages/rspack/src/config/zod.ts index b3e4ec53103..afb8ee3a64c 100644 --- a/packages/rspack/src/config/zod.ts +++ b/packages/rspack/src/config/zod.ts @@ -960,7 +960,15 @@ const experiments = z.strictObject({ incrementalRebuild: z.boolean().or(incrementalRebuildOptions).optional(), asyncWebAssembly: z.boolean().optional(), outputModule: z.boolean().optional(), - newSplitChunks: z.boolean().optional(), + newSplitChunks: z + .boolean() + .optional() + .refine(_ => { + console.warn( + "`experiments.newSplitChunks` will be removed at 0.4.0. See details at https://github.com/web-infra-dev/rspack/discussions/4168" + ); + return true; + }), css: z.boolean().optional(), futureDefaults: z.boolean().optional(), rspackFuture: rspackFutureOptions.optional() From effad1bfccf0ba4e00190655cbec3c1fd78aa95d Mon Sep 17 00:00:00 2001 From: zjk Date: Tue, 12 Sep 2023 00:24:07 +0800 Subject: [PATCH 07/49] fix(core): add AbstractMethodError and fix references (#4170) --- .../rspack/src/lib/AbstractMethodError.js | 49 +++++++++++++++++++ packages/rspack/src/util/hash/index.js | 4 +- 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 packages/rspack/src/lib/AbstractMethodError.js diff --git a/packages/rspack/src/lib/AbstractMethodError.js b/packages/rspack/src/lib/AbstractMethodError.js new file mode 100644 index 00000000000..bbf2d08a6c7 --- /dev/null +++ b/packages/rspack/src/lib/AbstractMethodError.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const WebpackError = require("./WebpackError"); +const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/; + +/** + * @param {string=} method method name + * @returns {string} message + */ +function createMessage(method) { + return `Abstract method${method ? " " + method : ""}. Must be overridden.`; +} + +/** + * @constructor + */ +function Message() { + /** @type {string} */ + this.stack = undefined; + Error.captureStackTrace(this); + /** @type {RegExpMatchArray} */ + const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP); + + this.message = match && match[1] ? createMessage(match[1]) : createMessage(); +} + +/** + * Error for abstract method + * @example + * class FooClass { + * abstractMethod() { + * throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overridden. + * } + * } + * + */ +class AbstractMethodError extends WebpackError { + constructor() { + super(new Message().message); + this.name = "AbstractMethodError"; + } +} + +module.exports = AbstractMethodError; diff --git a/packages/rspack/src/util/hash/index.js b/packages/rspack/src/util/hash/index.js index e7f00f9e666..08c103aa184 100644 --- a/packages/rspack/src/util/hash/index.js +++ b/packages/rspack/src/util/hash/index.js @@ -19,7 +19,7 @@ class Hash { * @returns {this} updated hash */ update(data, inputEncoding) { - const AbstractMethodError = require("../AbstractMethodError"); + const AbstractMethodError = require("../../lib/AbstractMethodError"); throw new AbstractMethodError(); } @@ -31,7 +31,7 @@ class Hash { * @returns {string|Buffer} digest */ digest(encoding) { - const AbstractMethodError = require("../AbstractMethodError"); + const AbstractMethodError = require("../../lib/AbstractMethodError"); throw new AbstractMethodError(); } } From a315f9bf5037907564cdf17f08639b1580b6c0c3 Mon Sep 17 00:00:00 2001 From: Hana Date: Tue, 12 Sep 2023 12:23:38 +0800 Subject: [PATCH 08/49] feat: improve zod types (#4173) --- packages/rspack/src/config/zod.ts | 65 +++++++++++-------------------- 1 file changed, 23 insertions(+), 42 deletions(-) diff --git a/packages/rspack/src/config/zod.ts b/packages/rspack/src/config/zod.ts index afb8ee3a64c..5284b47232c 100644 --- a/packages/rspack/src/config/zod.ts +++ b/packages/rspack/src/config/zod.ts @@ -337,20 +337,22 @@ export type Resolve = z.infer; //#endregion //#region Module -export type RuleSetCondition = - | RegExp - | string - | RuleSetConditions - | RuleSetLogicalConditions - | ((value: string) => boolean); -const ruleSetCondition: z.ZodType = z +const baseRuleSetCondition = z .instanceof(RegExp) .or(z.string()) - .or(z.lazy(() => ruleSetConditions)) - .or(z.lazy(() => ruleSetLogicalConditions)) .or(z.function().args(z.string()).returns(z.boolean())); +export type RuleSetCondition = + | z.infer + | RuleSetConditions + | RuleSetLogicalConditions; + +const ruleSetCondition: z.ZodType = baseRuleSetCondition + .or(z.lazy(() => ruleSetConditions)) + .or(z.lazy(() => ruleSetLogicalConditions)); + export type RuleSetConditions = RuleSetCondition[]; + const ruleSetConditions: z.ZodType = z.lazy(() => z.array(ruleSetCondition) ); @@ -360,6 +362,7 @@ export type RuleSetLogicalConditions = { or?: RuleSetConditions; not?: RuleSetConditions; }; + const ruleSetLogicalConditions: z.ZodType = z.strictObject({ and: ruleSetConditions.optional(), @@ -390,37 +393,7 @@ const ruleSetUse = ruleSetUseItem ); export type RuleSetUse = z.infer; -export type RuleSetRule = { - test?: RuleSetCondition; - exclude?: RuleSetCondition; - include?: RuleSetCondition; - issuer?: RuleSetCondition; - dependency?: RuleSetCondition; - resource?: RuleSetCondition; - resourceFragment?: RuleSetCondition; - resourceQuery?: RuleSetCondition; - scheme?: RuleSetCondition; - mimetype?: RuleSetCondition; - descriptionData?: { - [k: string]: RuleSetCondition; - }; - oneOf?: RuleSetRule[]; - rules?: RuleSetRule[]; - type?: string; - loader?: RuleSetLoader; - options?: RuleSetLoaderOptions; - use?: RuleSetUse; - parser?: { - [k: string]: any; - }; - generator?: { - [k: string]: any; - }; - resolve?: ResolveOptions; - sideEffects?: boolean; - enforce?: "pre" | "post"; -}; -const ruleSetRule: z.ZodType = z.strictObject({ +const baseRuleSetRule = z.strictObject({ test: ruleSetCondition.optional(), exclude: ruleSetCondition.optional(), include: ruleSetCondition.optional(), @@ -432,8 +405,6 @@ const ruleSetRule: z.ZodType = z.strictObject({ scheme: ruleSetCondition.optional(), mimetype: ruleSetCondition.optional(), descriptionData: z.record(ruleSetCondition).optional(), - oneOf: z.lazy(() => ruleSetRule.array()).optional(), - rules: z.lazy(() => ruleSetRule.array()).optional(), type: z.string().optional(), loader: ruleSetLoader.optional(), options: ruleSetLoaderOptions.optional(), @@ -445,6 +416,16 @@ const ruleSetRule: z.ZodType = z.strictObject({ enforce: z.literal("pre").or(z.literal("post")).optional() }); +export type RuleSetRule = z.infer & { + oneOf?: RuleSetRule[]; + rules?: RuleSetRule[]; +}; + +const ruleSetRule: z.ZodType = baseRuleSetRule.extend({ + oneOf: z.lazy(() => ruleSetRule.array()).optional(), + rules: z.lazy(() => ruleSetRule.array()).optional() +}); + const ruleSetRules = z.array(z.literal("...").or(ruleSetRule)); export type RuleSetRules = z.infer; From b5ae3a497523ad2ae8c823d5b05db01760a0d32d Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Tue, 12 Sep 2023 14:53:06 +0800 Subject: [PATCH 09/49] feat(config): only warn while `experiments.newSplitChunks` being explicitly setted (#4174) * feat(config): only warn while `experiments.newSplitChunks` being explicitly setted * Fix --- packages/rspack/src/config/zod.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/rspack/src/config/zod.ts b/packages/rspack/src/config/zod.ts index 5284b47232c..cab671dfae7 100644 --- a/packages/rspack/src/config/zod.ts +++ b/packages/rspack/src/config/zod.ts @@ -944,10 +944,12 @@ const experiments = z.strictObject({ newSplitChunks: z .boolean() .optional() - .refine(_ => { - console.warn( - "`experiments.newSplitChunks` will be removed at 0.4.0. See details at https://github.com/web-infra-dev/rspack/discussions/4168" - ); + .refine(val => { + if (val === false || val === true) { + console.warn( + "`experiments.newSplitChunks` will be removed at 0.4.0. See details at https://github.com/web-infra-dev/rspack/discussions/4168" + ); + } return true; }), css: z.boolean().optional(), From fbb45485d760cff72975e7cf288f3959ead1c16e Mon Sep 17 00:00:00 2001 From: Hana Date: Tue, 12 Sep 2023 17:23:21 +0800 Subject: [PATCH 10/49] ci: refine artifact publishing (#4178) --- scripts/build-npm.cjs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/scripts/build-npm.cjs b/scripts/build-npm.cjs index 6c5ad1ba0bf..a8542ea2759 100644 --- a/scripts/build-npm.cjs +++ b/scripts/build-npm.cjs @@ -82,6 +82,9 @@ try { fs.mkdirSync(NPM); } catch (e) {} +// Releasing bindings +const releasingPackages = []; + const bindings = fs .readdirSync(ARTIFACTS, { withFileTypes: true @@ -174,8 +177,30 @@ Rspack is [MIT licensed](https://github.com/web-infra-dev/rspack/blob/main/LICEN `; fs.writeFileSync(`${output}/README.md`, README); + releasingPackages.push(pkgJson.name); } +// Determine whether to release or not based on the CI build result. +// Validating not releasable bindings +fs.readdirSync(NPM, { + withFileTypes: true +}) + .filter(item => item.isDirectory()) + .map(item => path.join(NPM, item.name)) + .forEach(dir => { + const pkg = require(`${dir}/package.json`); + if (releasingPackages.includes(pkg.name)) { + // releasing + console.info(`Releasing package: ${pkg.name}`); + } else { + pkg.private = true; + console.info( + `Skipping package: ${pkg.name}. (Reason: local package, but its artifact is not available.)` + ); + fs.writeFileSync(`${dir}/package.json`, JSON.stringify(pkg, null, 2)); + } + }); + let bindingJsonPath = path.resolve( __dirname, "../crates/node_binding/package.json" From 32ab92d232d3e41ca068b0d788ea38d98b8227ec Mon Sep 17 00:00:00 2001 From: Gengkun Date: Tue, 12 Sep 2023 19:15:14 +0800 Subject: [PATCH 11/49] feat: compatible with html-webpack-plugin (#4175) * feat: export NodeTemplatePlugin and EnableChunkLoadingPlugin * feat: export EnableLibraryPlugin and EnableWasmLoadingPlugin * fix: entryOptions string error * feat: support __webpack_base_uri__ * feat: support optimizeTree hook * feat: __non_webpack_require__ * test: add html-webpack-plugin + html-loader test --- crates/node_binding/binding.d.ts | 23 +-- crates/node_binding/src/hook.rs | 2 + crates/node_binding/src/js_values/hooks.rs | 1 + crates/node_binding/src/plugins/mod.rs | 20 ++ .../src/options/raw_builtins/mod.rs | 40 +++- .../src/options/raw_output.rs | 184 +----------------- .../rspack_core/src/compiler/compilation.rs | 1 + crates/rspack_core/src/module.rs | 1 + crates/rspack_core/src/plugin/api.rs | 16 +- crates/rspack_core/src/plugin/args.rs | 10 +- .../rspack_core/src/plugin/plugin_driver.rs | 22 ++- crates/rspack_plugin_devtool/src/lib.rs | 16 +- .../src/plugin/api_plugin.rs | 27 +++ .../src/plugin/mod.rs | 1 + .../rspack_plugin_javascript/src/runtime.rs | 27 ++- .../src/visitors/dependency/api_scanner.rs | 37 +++- .../src/visitors/dependency/mod.rs | 2 + .../src/assign_library_plugin.rs | 32 ++- crates/rspack_plugin_library/src/lib.rs | 116 ++++++++++- .../src/common_js_chunk_format.rs | 2 +- examples/plugin-compat/package.json | 8 +- examples/plugin-compat/rspack.config.js | 2 +- packages/rspack/package.json | 3 + packages/rspack/src/Compilation.ts | 48 +++-- packages/rspack/src/Compiler.ts | 86 +++----- .../ArrayPushCallbackChunkFormatPlugin.ts | 6 + .../CommonJsChunkFormatPlugin.ts | 6 + .../EnableChunkLoadingPlugin.ts | 6 + .../src/builtin-plugin/EnableLibraryPlugin.ts | 6 + .../builtin-plugin/EnableWasmLoadingPlugin.ts | 6 + .../rspack/src/builtin-plugin/EntryPlugin.ts | 6 +- .../builtin-plugin/ModuleChunkFormatPlugin.ts | 6 + packages/rspack/src/builtin-plugin/base.ts | 6 + packages/rspack/src/builtin-plugin/index.ts | 6 + packages/rspack/src/config/adapter.ts | 1 - packages/rspack/src/index.ts | 18 +- packages/rspack/src/lib/LoaderTargetPlugin.js | 37 ++++ .../rspack/src/node/NodeTemplatePlugin.ts | 30 +++ packages/rspack/src/rspackOptionsApply.ts | 149 ++++++++++---- packages/rspack/src/util/fake.ts | 52 +++++ packages/rspack/tests/ConfigCase.template.ts | 8 +- .../__snapshots__/StatsTestCases.test.ts.snap | 4 +- .../plugins/html-webpack-plugin/index.js | 15 ++ .../plugins/html-webpack-plugin/template.html | 10 + .../plugins/html-webpack-plugin/template.pug | 9 + .../html-webpack-plugin/webpack.config.js | 21 ++ .../split-css-chunk-async/webpack.config.js | 20 +- pnpm-lock.yaml | 33 +--- .../asset-modules/base-uri/test.filter.js | 2 +- .../worker/web-worker/test.filter.js | 2 +- 50 files changed, 778 insertions(+), 414 deletions(-) create mode 100644 crates/rspack_plugin_javascript/src/plugin/api_plugin.rs create mode 100644 packages/rspack/src/builtin-plugin/ArrayPushCallbackChunkFormatPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/CommonJsChunkFormatPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/EnableChunkLoadingPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/EnableLibraryPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/EnableWasmLoadingPlugin.ts create mode 100644 packages/rspack/src/builtin-plugin/ModuleChunkFormatPlugin.ts create mode 100644 packages/rspack/src/lib/LoaderTargetPlugin.js create mode 100644 packages/rspack/src/node/NodeTemplatePlugin.ts create mode 100644 packages/rspack/tests/configCases/plugins/html-webpack-plugin/index.js create mode 100644 packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.html create mode 100644 packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.pug create mode 100644 packages/rspack/tests/configCases/plugins/html-webpack-plugin/webpack.config.js diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index 1f972a69bb3..b5d89c61635 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -123,6 +123,12 @@ export const enum BuiltinPluginName { ExternalsPlugin = 'ExternalsPlugin', NodeTargetPlugin = 'NodeTargetPlugin', ElectronTargetPlugin = 'ElectronTargetPlugin', + EnableChunkLoadingPlugin = 'EnableChunkLoadingPlugin', + EnableLibraryPlugin = 'EnableLibraryPlugin', + EnableWasmLoadingPlugin = 'EnableWasmLoadingPlugin', + CommonJsChunkFormatPlugin = 'CommonJsChunkFormatPlugin', + ArrayPushCallbackChunkFormatPlugin = 'ArrayPushCallbackChunkFormatPlugin', + ModuleChunkFormatPlugin = 'ModuleChunkFormatPlugin', HttpExternalsRspackPlugin = 'HttpExternalsRspackPlugin', CopyRspackPlugin = 'CopyRspackPlugin', HtmlRspackPlugin = 'HtmlRspackPlugin', @@ -234,6 +240,7 @@ export interface JsHooks { afterEmit: (...args: any[]) => any make: (...args: any[]) => any optimizeModules: (...args: any[]) => any + optimizeTree: (...args: any[]) => any optimizeChunkModule: (...args: any[]) => any beforeCompile: (...args: any[]) => any afterCompile: (...args: any[]) => any @@ -433,13 +440,6 @@ export interface JsStatsWarning { formatted: string } -export interface NodeFS { - writeFile: (...args: any[]) => any - removeFile: (...args: any[]) => any - mkdir: (...args: any[]) => any - mkdirp: (...args: any[]) => any -} - export interface PathData { filename?: string hash?: string @@ -875,7 +875,6 @@ export interface RawOutputOptions { importFunctionName: string iife: boolean module: boolean - chunkFormat: string chunkLoading: string enabledChunkLoadingTypes?: Array trustedTypes?: RawTrustedTypes @@ -1052,11 +1051,3 @@ export function registerGlobalTrace(filter: string, layer: "chrome" | "logger", /** Builtin loader runner */ export function runBuiltinLoader(builtin: string, options: string | undefined | null, loaderContext: JsLoaderContext): Promise -export interface ThreadsafeNodeFS { - writeFile: (...args: any[]) => any - removeFile: (...args: any[]) => any - mkdir: (...args: any[]) => any - mkdirp: (...args: any[]) => any - removeDirAll: (...args: any[]) => any -} - diff --git a/crates/node_binding/src/hook.rs b/crates/node_binding/src/hook.rs index 0fdcd4f6a87..84efc897e7d 100644 --- a/crates/node_binding/src/hook.rs +++ b/crates/node_binding/src/hook.rs @@ -32,6 +32,7 @@ pub enum Hook { AfterCompile, FinishModules, OptimizeModules, + OptimizaTree, /// webpack `compilation.hooks.chunkAsset` ChunkAsset, NormalModuleFactoryResolveForScheme, @@ -73,6 +74,7 @@ impl From for Hook { "afterCompile" => Hook::AfterCompile, "finishModules" => Hook::FinishModules, "optimizeModules" => Hook::OptimizeModules, + "optimizaTree" => Hook::OptimizaTree, "chunkAsset" => Hook::ChunkAsset, "normalModuleFactoryResolveForScheme" => Hook::NormalModuleFactoryResolveForScheme, "afterResolve" => Hook::AfterResolve, diff --git a/crates/node_binding/src/js_values/hooks.rs b/crates/node_binding/src/js_values/hooks.rs index 64e178e9b2a..3a401a52603 100644 --- a/crates/node_binding/src/js_values/hooks.rs +++ b/crates/node_binding/src/js_values/hooks.rs @@ -25,6 +25,7 @@ pub struct JsHooks { pub after_emit: JsFunction, pub make: JsFunction, pub optimize_modules: JsFunction, + pub optimize_tree: JsFunction, pub optimize_chunk_module: JsFunction, pub before_compile: JsFunction, pub after_compile: JsFunction, diff --git a/crates/node_binding/src/plugins/mod.rs b/crates/node_binding/src/plugins/mod.rs index e70ce25eb36..b18d379ca31 100644 --- a/crates/node_binding/src/plugins/mod.rs +++ b/crates/node_binding/src/plugins/mod.rs @@ -46,6 +46,7 @@ pub struct JsHooksAdapter { pub asset_emitted_tsfn: ThreadsafeFunction, pub after_emit_tsfn: ThreadsafeFunction<(), ()>, pub optimize_modules_tsfn: ThreadsafeFunction, + pub optimize_tree_tsfn: ThreadsafeFunction<(), ()>, pub optimize_chunk_modules_tsfn: ThreadsafeFunction, pub before_compile_tsfn: ThreadsafeFunction<(), ()>, pub after_compile_tsfn: ThreadsafeFunction, @@ -534,6 +535,21 @@ impl rspack_core::Plugin for JsHooksAdapter { .map_err(|err| internal_error!("Failed to call optimize modules: {err}"))? } + async fn optimize_tree( + &self, + _compilation: &mut rspack_core::Compilation, + ) -> rspack_error::Result<()> { + if self.is_hook_disabled(&Hook::OptimizaTree) { + return Ok(()); + } + self + .optimize_tree_tsfn + .call((), ThreadsafeFunctionCallMode::NonBlocking) + .into_rspack_result()? + .await + .map_err(|err| internal_error!("Failed to call optimize tree: {err}",))? + } + async fn optimize_chunk_modules( &self, args: rspack_core::OptimizeChunksArgs<'_>, @@ -753,6 +769,7 @@ impl JsHooksAdapter { asset_emitted, after_emit, optimize_modules, + optimize_tree, optimize_chunk_module, before_resolve, after_resolve, @@ -811,6 +828,8 @@ impl JsHooksAdapter { let make_tsfn: ThreadsafeFunction<(), ()> = js_fn_into_threadsafe_fn!(make, env); let optimize_modules_tsfn: ThreadsafeFunction = js_fn_into_threadsafe_fn!(optimize_modules, env); + let optimize_tree_tsfn: ThreadsafeFunction<(), ()> = + js_fn_into_threadsafe_fn!(optimize_tree, env); let optimize_chunk_modules_tsfn: ThreadsafeFunction = js_fn_into_threadsafe_fn!(optimize_chunk_module, env); let before_compile_tsfn: ThreadsafeFunction<(), ()> = @@ -865,6 +884,7 @@ impl JsHooksAdapter { asset_emitted_tsfn, after_emit_tsfn, optimize_modules_tsfn, + optimize_tree_tsfn, optimize_chunk_modules_tsfn, before_compile_tsfn, after_compile_tsfn, diff --git a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs index 7c7ab2f6e04..33d1e732436 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs @@ -20,9 +20,15 @@ use rspack_plugin_externals::{ electron_target_plugin, http_externals_rspack_plugin, node_target_plugin, ExternalsPlugin, }; use rspack_plugin_html::HtmlRspackPlugin; +use rspack_plugin_library::enable_library_plugin; use rspack_plugin_progress::ProgressPlugin; +use rspack_plugin_runtime::{ + enable_chunk_loading_plugin, ArrayPushCallbackChunkFormatPlugin, CommonJsChunkFormatPlugin, + ModuleChunkFormatPlugin, +}; use rspack_plugin_swc_css_minimizer::SwcCssMinimizerRspackPlugin; use rspack_plugin_swc_js_minimizer::SwcJsMinimizerRspackPlugin; +use rspack_plugin_wasm::enable_wasm_loading_plugin; pub use self::{ raw_banner::RawBannerPluginOptions, raw_copy::RawCopyRspackPluginOptions, @@ -46,6 +52,12 @@ pub enum BuiltinPluginName { ExternalsPlugin, NodeTargetPlugin, ElectronTargetPlugin, + EnableChunkLoadingPlugin, + EnableLibraryPlugin, + EnableWasmLoadingPlugin, + CommonJsChunkFormatPlugin, + ArrayPushCallbackChunkFormatPlugin, + ModuleChunkFormatPlugin, // rspack specific plugins HttpExternalsRspackPlugin, @@ -69,6 +81,7 @@ impl RawOptionsApply for BuiltinPlugin { plugins: &mut Vec, ) -> std::result::Result { match self.name { + // webpack also have these plugins BuiltinPluginName::DefinePlugin => { let plugin = DefinePlugin::new(downcast_into::(self.options)?).boxed(); plugins.push(plugin); @@ -110,8 +123,33 @@ impl RawOptionsApply for BuiltinPlugin { BuiltinPluginName::NodeTargetPlugin => plugins.push(node_target_plugin()), BuiltinPluginName::ElectronTargetPlugin => { let context = downcast_into::(self.options)?; - electron_target_plugin(context.into(), plugins) + electron_target_plugin(context.into(), plugins); + } + BuiltinPluginName::EnableChunkLoadingPlugin => { + let chunk_loading_type = downcast_into::(self.options)?; + enable_chunk_loading_plugin(chunk_loading_type.as_str().into(), plugins); + } + BuiltinPluginName::EnableLibraryPlugin => { + let library_type = downcast_into::(self.options)?; + enable_library_plugin(library_type, plugins); + } + BuiltinPluginName::EnableWasmLoadingPlugin => { + let wasm_loading_type = downcast_into::(self.options)?; + plugins.push(enable_wasm_loading_plugin( + wasm_loading_type.as_str().into(), + )); } + BuiltinPluginName::CommonJsChunkFormatPlugin => { + plugins.push(CommonJsChunkFormatPlugin.boxed()); + } + BuiltinPluginName::ArrayPushCallbackChunkFormatPlugin => { + plugins.push(ArrayPushCallbackChunkFormatPlugin.boxed()); + } + BuiltinPluginName::ModuleChunkFormatPlugin => { + plugins.push(ModuleChunkFormatPlugin.boxed()); + } + + // rspack specific plugins BuiltinPluginName::HttpExternalsRspackPlugin => { let plugin_options = downcast_into::(self.options)?; let plugin = http_externals_rspack_plugin(plugin_options.css); diff --git a/crates/rspack_binding_options/src/options/raw_output.rs b/crates/rspack_binding_options/src/options/raw_output.rs index fb4a28834da..d35173d953a 100644 --- a/crates/rspack_binding_options/src/options/raw_output.rs +++ b/crates/rspack_binding_options/src/options/raw_output.rs @@ -1,9 +1,8 @@ use napi_derive::napi; use rspack_core::{ to_identifier, BoxPlugin, CrossOriginLoading, LibraryAuxiliaryComment, LibraryName, - LibraryOptions, OutputOptions, PluginExt, TrustedTypes, + LibraryOptions, OutputOptions, TrustedTypes, }; -use rspack_error::internal_error; use serde::Deserialize; use crate::RawOptionsApply; @@ -138,7 +137,6 @@ pub struct RawOutputOptions { pub import_function_name: String, pub iife: bool, pub module: bool, - pub chunk_format: String, pub chunk_loading: String, pub enabled_chunk_loading_types: Option>, pub trusted_types: Option, @@ -155,23 +153,7 @@ pub struct RawOutputOptions { impl RawOptionsApply for RawOutputOptions { type Options = OutputOptions; - fn apply(self, plugins: &mut Vec) -> Result { - self.apply_chunk_format_plugin(plugins)?; - if let Some(chunk_loading_types) = self.enabled_chunk_loading_types.as_ref() { - for chunk_loading_type in chunk_loading_types { - rspack_plugin_runtime::enable_chunk_loading_plugin( - chunk_loading_type.as_str().into(), - plugins, - ); - } - } - self.apply_library_plugin(plugins); - for wasm_loading_type in self.enabled_wasm_loading_types { - plugins.push(rspack_plugin_wasm::enable_wasm_loading_plugin( - wasm_loading_type.as_str().into(), - )); - } - + fn apply(self, _: &mut Vec) -> Result { Ok(OutputOptions { path: self.path.into(), clean: self.clean, @@ -209,165 +191,3 @@ impl RawOptionsApply for RawOutputOptions { }) } } - -impl RawOutputOptions { - fn apply_chunk_format_plugin( - &self, - plugins: &mut Vec, - ) -> Result<(), rspack_error::Error> { - match self.chunk_format.as_str() { - "array-push" => { - plugins.push(rspack_plugin_runtime::ArrayPushCallbackChunkFormatPlugin {}.boxed()); - } - "commonjs" => plugins.push(rspack_plugin_runtime::CommonJsChunkFormatPlugin {}.boxed()), - "module" => { - plugins.push(rspack_plugin_runtime::ModuleChunkFormatPlugin {}.boxed()); - } - "false" => {} - _ => { - return Err(internal_error!( - "Unsupported chunk format '{}'", - self.chunk_format - )) - } - } - Ok(()) - } - - fn apply_library_plugin(&self, plugins: &mut Vec) { - if let Some(enabled_library_types) = &self.enabled_library_types { - for library in enabled_library_types { - match library.as_str() { - "var" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec![], - declare: true, - unnamed: rspack_plugin_library::Unnamed::Error, - named: None, - }, - ) - .boxed(), - ); - } - "assign-properties" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec![], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Error, - named: Some(rspack_plugin_library::Named::Copy), - }, - ) - .boxed(), - ); - } - "assign" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec![], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Error, - named: None, - }, - ) - .boxed(), - ); - } - "this" | "window" | "self" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec![library.to_string()], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Copy, - named: None, - }, - ) - .boxed(), - ); - } - "global" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec![self.global_object.clone()], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Copy, - named: None, - }, - ) - .boxed(), - ); - } - "commonjs" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec!["exports".to_string()], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Copy, - named: None, - }, - ) - .boxed(), - ); - } - "commonjs-static" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec!["exports".to_string()], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Static, - named: None, - }, - ) - .boxed(), - ); - } - "commonjs2" | "commonjs-module" => { - plugins.push( - rspack_plugin_library::AssignLibraryPlugin::new( - rspack_plugin_library::AssignLibraryPluginOptions { - library_type: library.clone(), - prefix: vec!["module".to_string(), "exports".to_string()], - declare: false, - unnamed: rspack_plugin_library::Unnamed::Assign, - named: None, - }, - ) - .boxed(), - ); - } - "umd" | "umd2" => { - plugins.push(rspack_plugin_library::ExportPropertyLibraryPlugin::default().boxed()); - plugins.push(rspack_plugin_library::UmdLibraryPlugin::new("umd2".eq(library)).boxed()); - } - "amd" | "amd-require" => { - plugins.push(rspack_plugin_library::ExportPropertyLibraryPlugin::default().boxed()); - plugins.push( - rspack_plugin_library::AmdLibraryPlugin::new("amd-require".eq(library)).boxed(), - ); - } - "module" => { - plugins.push(rspack_plugin_library::ExportPropertyLibraryPlugin::default().boxed()); - plugins.push(rspack_plugin_library::ModuleLibraryPlugin::default().boxed()); - } - "system" => plugins.push(rspack_plugin_library::SystemLibraryPlugin::default().boxed()), - _ => {} - } - } - } - } -} diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index 8476e0f0bf2..d1677c7aad9 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -1161,6 +1161,7 @@ impl Compilation { logger.time_end(start); let start = logger.time("optimize"); + plugin_driver.optimize_tree(self).await?; plugin_driver.optimize_chunk_modules(self).await?; logger.time_end(start); diff --git a/crates/rspack_core/src/module.rs b/crates/rspack_core/src/module.rs index a7418582e98..7d8a142059a 100644 --- a/crates/rspack_core/src/module.rs +++ b/crates/rspack_core/src/module.rs @@ -46,6 +46,7 @@ pub struct BuildInfo { pub asset_filenames: HashSet, pub harmony_named_exports: HashSet, pub all_star_exports: Vec, + pub need_create_require: bool, } #[derive(Debug, Default, Clone, Hash)] diff --git a/crates/rspack_core/src/plugin/api.rs b/crates/rspack_core/src/plugin/api.rs index 9bca72db1b4..3ff4cd10040 100644 --- a/crates/rspack_core/src/plugin/api.rs +++ b/crates/rspack_core/src/plugin/api.rs @@ -35,7 +35,7 @@ pub type PluginRenderChunkHookOutput = Result>; pub type PluginProcessAssetsOutput = Result<()>; pub type PluginOptimizeChunksOutput = Result<()>; pub type PluginAdditionalChunkRuntimeRequirementsOutput = Result<()>; -pub type PluginRenderModuleContentOutput = Result>; +pub type PluginRenderModuleContentOutput<'a> = Result>; pub type PluginRenderStartupHookOutput = Result>; pub type PluginRenderHookOutput = Result>; pub type PluginJsChunkHashHookOutput = Result<()>; @@ -189,12 +189,12 @@ pub trait Plugin: Debug + Send + Sync { } // JavascriptModulesPlugin hook - fn render_module_content( - &self, + fn render_module_content<'a>( + &'a self, _ctx: PluginContext, - _args: &RenderModuleContentArgs, - ) -> PluginRenderModuleContentOutput { - Ok(None) + args: RenderModuleContentArgs<'a>, + ) -> PluginRenderModuleContentOutput<'a> { + Ok(args) } // JavascriptModulesPlugin hook @@ -370,6 +370,10 @@ pub trait Plugin: Debug + Send + Sync { Ok(()) } + async fn optimize_tree(&self, _compilation: &mut Compilation) -> Result<()> { + Ok(()) + } + async fn optimize_chunk_modules(&self, _args: OptimizeChunksArgs<'_>) -> Result<()> { Ok(()) } diff --git a/crates/rspack_core/src/plugin/args.rs b/crates/rspack_core/src/plugin/args.rs index 0c1ab87dc02..5e67ffea144 100644 --- a/crates/rspack_core/src/plugin/args.rs +++ b/crates/rspack_core/src/plugin/args.rs @@ -9,9 +9,9 @@ use rustc_hash::FxHashSet as HashSet; use crate::ast::css::Ast as CssAst; use crate::ast::javascript::Ast as JsAst; use crate::{ - Chunk, ChunkUkey, Compilation, Context, DependencyCategory, DependencyType, ErrorSpan, - FactoryMeta, ModuleDependency, ModuleIdentifier, Resolve, RuntimeGlobals, SharedPluginDriver, - Stats, + Chunk, ChunkInitFragments, ChunkUkey, Compilation, Context, DependencyCategory, DependencyType, + ErrorSpan, FactoryMeta, ModuleDependency, ModuleGraphModule, ModuleIdentifier, Resolve, + RuntimeGlobals, SharedPluginDriver, Stats, }; // #[derive(Debug)] // pub struct ParseModuleArgs<'a> { @@ -235,8 +235,10 @@ impl<'me> RenderChunkArgs<'me> { #[derive(Debug)] pub struct RenderModuleContentArgs<'a> { - pub module_source: &'a BoxSource, + pub module_source: BoxSource, + pub chunk_init_fragments: ChunkInitFragments, pub compilation: &'a Compilation, + pub module_graph_module: &'a ModuleGraphModule, } #[derive(Debug)] diff --git a/crates/rspack_core/src/plugin/plugin_driver.rs b/crates/rspack_core/src/plugin/plugin_driver.rs index d0437ec0f18..3c54761e27b 100644 --- a/crates/rspack_core/src/plugin/plugin_driver.rs +++ b/crates/rspack_core/src/plugin/plugin_driver.rs @@ -294,16 +294,14 @@ impl PluginDriver { Ok(()) } - pub fn render_module_content( - &self, - args: RenderModuleContentArgs, - ) -> PluginRenderModuleContentOutput { + pub fn render_module_content<'a>( + &'a self, + mut args: RenderModuleContentArgs<'a>, + ) -> PluginRenderModuleContentOutput<'a> { for plugin in &self.plugins { - if let Some(source) = plugin.render_module_content(PluginContext::new(), &args)? { - return Ok(Some(source)); - } + args = plugin.render_module_content(PluginContext::new(), args)?; } - Ok(None) + Ok(args) } pub async fn factorize( @@ -501,6 +499,14 @@ impl PluginDriver { Ok(()) } + #[instrument(name = "plugin:optimize_tree", skip_all)] + pub async fn optimize_tree(&self, compilation: &mut Compilation) -> Result<()> { + for plugin in &self.plugins { + plugin.optimize_tree(compilation).await?; + } + Ok(()) + } + #[instrument(name = "plugin:optimize_chunk_modules", skip_all)] pub async fn optimize_chunk_modules(&self, compilation: &mut Compilation) -> Result<()> { for plugin in &self.plugins { diff --git a/crates/rspack_plugin_devtool/src/lib.rs b/crates/rspack_plugin_devtool/src/lib.rs index 9cacb81e906..d2b4867b8e6 100644 --- a/crates/rspack_plugin_devtool/src/lib.rs +++ b/crates/rspack_plugin_devtool/src/lib.rs @@ -68,23 +68,25 @@ impl Plugin for DevtoolPlugin { "rspack.DevtoolPlugin" } - fn render_module_content( - &self, + fn render_module_content<'a>( + &'a self, _ctx: PluginContext, - args: &RenderModuleContentArgs, - ) -> PluginRenderModuleContentOutput { + mut args: RenderModuleContentArgs<'a>, + ) -> PluginRenderModuleContentOutput<'a> { let devtool = &args.compilation.options.devtool; let origin_source = args.module_source.clone(); if devtool.eval() && devtool.source_map() { if let Some(cached) = MODULE_RENDER_CACHE.get(&origin_source) { - return Ok(Some(cached.value().clone())); + args.module_source = cached.value().clone(); + return Ok(args); } else if let Some(map) = origin_source.map(&MapOptions::new(devtool.cheap())) { let source = wrap_eval_source_map(&origin_source.source(), map, args.compilation)?; MODULE_RENDER_CACHE.insert(origin_source, source.clone()); - return Ok(Some(source)); + args.module_source = source; + return Ok(args); } } - Ok(Some(origin_source)) + Ok(args) } fn js_chunk_hash( diff --git a/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs new file mode 100644 index 00000000000..731779dd050 --- /dev/null +++ b/crates/rspack_plugin_javascript/src/plugin/api_plugin.rs @@ -0,0 +1,27 @@ +use rspack_core::{ + InitFragmentStage, NormalInitFragment, Plugin, PluginContext, PluginRenderModuleContentOutput, + RenderModuleContentArgs, +}; + +#[derive(Debug)] +pub struct APIPlugin; + +impl Plugin for APIPlugin { + fn render_module_content<'a>( + &'a self, + _ctx: PluginContext, + mut args: RenderModuleContentArgs<'a>, + ) -> PluginRenderModuleContentOutput<'a> { + if let Some(build_info) = &args.module_graph_module.build_info && build_info.need_create_require { + args.chunk_init_fragments + .entry("external module node-commonjs".to_string()) + .or_insert(NormalInitFragment::new( + "import { createRequire as __WEBPACK_EXTERNAL_createRequire } from 'module';\n" + .to_string(), + InitFragmentStage::StageHarmonyImports, + None, + )); + } + Ok(args) + } +} diff --git a/crates/rspack_plugin_javascript/src/plugin/mod.rs b/crates/rspack_plugin_javascript/src/plugin/mod.rs index 2085384fea6..4d82856d693 100644 --- a/crates/rspack_plugin_javascript/src/plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/plugin/mod.rs @@ -1,3 +1,4 @@ +pub mod api_plugin; pub mod flag_usage_plugin; pub mod impl_plugin_for_js_plugin; pub mod infer_async_modules_plugin; diff --git a/crates/rspack_plugin_javascript/src/runtime.rs b/crates/rspack_plugin_javascript/src/runtime.rs index 9323f758823..c046d6c85f2 100644 --- a/crates/rspack_plugin_javascript/src/runtime.rs +++ b/crates/rspack_plugin_javascript/src/runtime.rs @@ -35,17 +35,14 @@ pub fn render_chunk_modules( .get(&mgm.module_identifier, Some(&chunk.runtime)) .expect("should have code generation result"); if let Some(origin_source) = code_gen_result.get(&SourceType::JavaScript) { - let module_source = if let Some(source) = plugin_driver + let render_module_result = plugin_driver .render_module_content(RenderModuleContentArgs { compilation, - module_source: origin_source, + module_graph_module: mgm, + module_source: origin_source.clone(), + chunk_init_fragments: ChunkInitFragments::default(), }) - .expect("render_module_content failed") - { - source - } else { - origin_source.clone() - }; + .expect("render_module_content failed"); let runtime_requirements = compilation .chunk_graph @@ -54,12 +51,13 @@ pub fn render_chunk_modules( Some(( mgm.module_identifier, render_module( - module_source, + render_module_result.module_source, mgm, runtime_requirements, mgm.id(&compilation.chunk_graph), ), &code_gen_result.chunk_init_fragments, + render_module_result.chunk_init_fragments, )) } else { None @@ -67,21 +65,20 @@ pub fn render_chunk_modules( }) .collect::>(); - module_code_array.sort_unstable_by_key(|(module_identifier, _, _)| *module_identifier); + module_code_array.sort_unstable_by_key(|(module_identifier, _, _, _)| *module_identifier); let chunk_init_fragments = module_code_array.iter().fold( ChunkInitFragments::default(), - |mut chunk_init_fragments, (_, _, fragments)| { - for (k, v) in fragments.iter() { - chunk_init_fragments.insert(k.to_string(), v.clone()); - } + |mut chunk_init_fragments, (_, _, fragments, additional_fragments)| { + chunk_init_fragments.extend((*fragments).clone()); + chunk_init_fragments.extend(additional_fragments.clone()); chunk_init_fragments }, ); let module_sources: Vec<_> = module_code_array .into_iter() - .map(|(_, source, _)| source) + .map(|(_, source, _, _)| source) .collect::>()?; let module_sources = module_sources .into_par_iter() diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/api_scanner.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/api_scanner.rs index 6e6d015dea3..8a495c77c0d 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/api_scanner.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/api_scanner.rs @@ -1,6 +1,6 @@ use rspack_core::{ - ConstDependency, DependencyTemplate, ResourceData, RuntimeGlobals, RuntimeRequirementsDependency, - SpanExt, + BuildInfo, ConstDependency, DependencyTemplate, ResourceData, RuntimeGlobals, + RuntimeRequirementsDependency, SpanExt, }; use swc_core::{ common::{Spanned, SyntaxContext}, @@ -18,9 +18,13 @@ pub const WEBPACK_MODULES: &str = "__webpack_modules__"; pub const WEBPACK_MODULE: &str = "__webpack_module__"; pub const WEBPACK_RESOURCE_QUERY: &str = "__resourceQuery"; pub const WEBPACK_CHUNK_LOAD: &str = "__webpack_chunk_load__"; +pub const WEBPACK_BASE_URI: &str = "__webpack_base_uri__"; +pub const NON_WEBPACK_REQUIRE: &str = "__non_webpack_require__"; pub struct ApiScanner<'a> { pub unresolved_ctxt: &'a SyntaxContext, + pub module: bool, + pub build_info: &'a mut BuildInfo, pub enter_assign: bool, pub resource_data: &'a ResourceData, pub presentational_dependencies: &'a mut Vec>, @@ -31,9 +35,13 @@ impl<'a> ApiScanner<'a> { unresolved_ctxt: &'a SyntaxContext, resource_data: &'a ResourceData, presentational_dependencies: &'a mut Vec>, + module: bool, + build_info: &'a mut BuildInfo, ) -> Self { Self { unresolved_ctxt, + module, + build_info, enter_assign: false, resource_data, presentational_dependencies, @@ -141,6 +149,31 @@ impl Visit for ApiScanner<'_> { None, ))); } + WEBPACK_BASE_URI => { + self + .presentational_dependencies + .push(Box::new(ConstDependency::new( + ident.span.real_lo(), + ident.span.real_hi(), + RuntimeGlobals::BASE_URI.name().into(), + Some(RuntimeGlobals::BASE_URI), + ))); + } + NON_WEBPACK_REQUIRE => { + self + .presentational_dependencies + .push(Box::new(ConstDependency::new( + ident.span.real_lo(), + ident.span.real_hi(), + if self.module { + self.build_info.need_create_require = true; + "__WEBPACK_EXTERNAL_createRequire(import.meta.url)".into() + } else { + "require".into() + }, + None, + ))); + } _ => {} } } diff --git a/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs b/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs index 24c702aaf07..6cb7c6fde72 100644 --- a/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs +++ b/crates/rspack_plugin_javascript/src/visitors/dependency/mod.rs @@ -58,6 +58,8 @@ pub fn scan_dependencies( &unresolved_ctxt, resource_data, &mut presentational_dependencies, + compiler_options.output.module, + build_info, )); program.visit_with(&mut CompatibilityScanner::new( diff --git a/crates/rspack_plugin_library/src/assign_library_plugin.rs b/crates/rspack_plugin_library/src/assign_library_plugin.rs index 3b3dfa9e8f1..05ba332adcb 100644 --- a/crates/rspack_plugin_library/src/assign_library_plugin.rs +++ b/crates/rspack_plugin_library/src/assign_library_plugin.rs @@ -29,10 +29,36 @@ pub enum Named { Assign, } +#[derive(Debug)] +pub enum Prefix { + Global, + Array(Vec), +} + +impl Prefix { + pub fn value(&self, compilation: &Compilation) -> Vec { + match self { + Prefix::Global => vec![compilation.options.output.global_object.clone()], + Prefix::Array(v) => v.clone(), + } + } + + pub fn len(&self) -> usize { + match self { + Prefix::Global => 1, + Prefix::Array(v) => v.len(), + } + } + + pub fn is_empty(&self) -> bool { + self.len() == 0 + } +} + #[derive(Debug)] pub struct AssignLibraryPluginOptions { pub library_type: String, - pub prefix: Vec, + pub prefix: Prefix, pub declare: bool, pub unnamed: Unnamed, pub named: Option, @@ -52,7 +78,7 @@ impl AssignLibraryPlugin { if let Some(library) = &compilation.options.output.library { if let Some(name) = &library.name { if let Some(root) = &name.root { - let mut prefix = self.options.prefix.clone(); + let mut prefix = self.options.prefix.value(compilation); prefix.extend( root .iter() @@ -73,7 +99,7 @@ impl AssignLibraryPlugin { } } } - self.options.prefix.clone() + self.options.prefix.value(compilation) } } diff --git a/crates/rspack_plugin_library/src/lib.rs b/crates/rspack_plugin_library/src/lib.rs index 0172b680cb0..6b2633c1563 100644 --- a/crates/rspack_plugin_library/src/lib.rs +++ b/crates/rspack_plugin_library/src/lib.rs @@ -1,14 +1,114 @@ -mod assign_library_plugin; -pub use assign_library_plugin::*; -mod umd_library_plugin; -pub use umd_library_plugin::UmdLibraryPlugin; mod amd_library_plugin; -pub use amd_library_plugin::AmdLibraryPlugin; -mod module_library_plugin; -pub use module_library_plugin::ModuleLibraryPlugin; +mod assign_library_plugin; mod export_property_plugin; -pub use system_library_plugin::SystemLibraryPlugin; +mod module_library_plugin; mod system_library_plugin; +mod umd_library_plugin; mod utils; +pub use amd_library_plugin::AmdLibraryPlugin; +pub use assign_library_plugin::*; pub use export_property_plugin::ExportPropertyLibraryPlugin; +pub use module_library_plugin::ModuleLibraryPlugin; +use rspack_core::{BoxPlugin, PluginExt}; +pub use system_library_plugin::SystemLibraryPlugin; +pub use umd_library_plugin::UmdLibraryPlugin; + +pub fn enable_library_plugin(library_type: String, plugins: &mut Vec) { + match library_type.as_str() { + "var" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Array(vec![]), + declare: true, + unnamed: Unnamed::Error, + named: None, + }) + .boxed(), + ), + "assign-properties" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Array(vec![]), + declare: false, + unnamed: Unnamed::Error, + named: Some(Named::Copy), + }) + .boxed(), + ), + "assign" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Array(vec![]), + declare: false, + unnamed: Unnamed::Error, + named: None, + }) + .boxed(), + ), + "this" | "window" | "self" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type: library_type.clone(), + prefix: Prefix::Array(vec![library_type]), + declare: false, + unnamed: Unnamed::Copy, + named: None, + }) + .boxed(), + ), + "global" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Global, + declare: false, + unnamed: Unnamed::Copy, + named: None, + }) + .boxed(), + ), + "commonjs" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Array(vec!["exports".to_string()]), + declare: false, + unnamed: Unnamed::Copy, + named: None, + }) + .boxed(), + ), + "commonjs-static" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Array(vec!["exports".to_string()]), + declare: false, + unnamed: Unnamed::Static, + named: None, + }) + .boxed(), + ), + "commonjs2" | "commonjs-module" => plugins.push( + AssignLibraryPlugin::new(AssignLibraryPluginOptions { + library_type, + prefix: Prefix::Array(vec!["module".to_string(), "exports".to_string()]), + declare: false, + unnamed: Unnamed::Assign, + named: None, + }) + .boxed(), + ), + "umd" | "umd2" => { + plugins.push(ExportPropertyLibraryPlugin::default().boxed()); + plugins.push(UmdLibraryPlugin::new("umd2".eq(&library_type)).boxed()); + } + "amd" | "amd-require" => { + plugins.push(ExportPropertyLibraryPlugin::default().boxed()); + plugins.push(AmdLibraryPlugin::new("amd-require".eq(&library_type)).boxed()); + } + "module" => { + plugins.push(ExportPropertyLibraryPlugin::default().boxed()); + plugins.push(ModuleLibraryPlugin::default().boxed()); + } + "system" => plugins.push(SystemLibraryPlugin::default().boxed()), + _ => {} + } +} diff --git a/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs b/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs index 90e38efcb4b..7c924784c98 100644 --- a/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs +++ b/crates/rspack_plugin_runtime/src/common_js_chunk_format.rs @@ -21,7 +21,7 @@ pub struct CommonJsChunkFormatPlugin; #[async_trait] impl Plugin for CommonJsChunkFormatPlugin { fn name(&self) -> &'static str { - "CommonJsChunkFormatPlugin" + "rspack.CommonJsChunkFormatPlugin" } fn additional_chunk_runtime_requirements( diff --git a/examples/plugin-compat/package.json b/examples/plugin-compat/package.json index 85ef4d97bf6..0b6220322e7 100644 --- a/examples/plugin-compat/package.json +++ b/examples/plugin-compat/package.json @@ -13,14 +13,14 @@ "license": "ISC", "devDependencies": { "@rspack/cli": "workspace:*", - "@rspack/plugin-html": "workspace:*", "@rspack/plugin-minify": "workspace:*", "copy-webpack-plugin": "5.1.2", + "fork-ts-checker-webpack-plugin": "8.0.0", "generate-package-json-webpack-plugin": "^2.6.0", + "html-webpack-plugin": "^5.5.0", "license-webpack-plugin": "^4.0.2", - "webpack-bundle-analyzer": "4.7.0", - "webpack-stats-plugin": "1.1.1", "rspack-manifest-plugin": "5.0.0-alpha0", - "fork-ts-checker-webpack-plugin": "8.0.0" + "webpack-bundle-analyzer": "4.7.0", + "webpack-stats-plugin": "1.1.1" } } diff --git a/examples/plugin-compat/rspack.config.js b/examples/plugin-compat/rspack.config.js index 02a55ec0f7f..14b35f07363 100644 --- a/examples/plugin-compat/rspack.config.js +++ b/examples/plugin-compat/rspack.config.js @@ -1,7 +1,7 @@ const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; const CopyPlugin = require("copy-webpack-plugin"); -const HtmlPlugin = require("@rspack/plugin-html").default; +const HtmlPlugin = require("html-webpack-plugin") const { StatsWriterPlugin } = require("webpack-stats-plugin"); const minifyPlugin = require("@rspack/plugin-minify"); const manifestPlugin = require("rspack-manifest-plugin").WebpackManifestPlugin; diff --git a/packages/rspack/package.json b/packages/rspack/package.json index 71fc60fd230..d09ca72cf7d 100644 --- a/packages/rspack/package.json +++ b/packages/rspack/package.json @@ -39,11 +39,14 @@ "copy-webpack-plugin": "5", "cross-env": "^7.0.3", "file-loader": "^6.2.0", + "html-loader": "^4.2.0", + "html-webpack-plugin": "^5.5.0", "jest-serializer-path": "^0.1.15", "less": "4.1.3", "less-loader": "^11.1.0", "postcss-loader": "^7.0.2", "postcss-pxtorem": "^6.0.0", + "pug-loader": "^2.4.0", "react-relay": "^14.1.0", "sass": "^1.56.2", "sass-loader": "^13.2.0", diff --git a/packages/rspack/src/Compilation.ts b/packages/rspack/src/Compilation.ts index 14e761a0d44..cf7c13b003d 100644 --- a/packages/rspack/src/Compilation.ts +++ b/packages/rspack/src/Compilation.ts @@ -49,7 +49,8 @@ import { concatErrorMsgAndStack, isJsStatsError, toJsAssetInfo } from "./util"; import { createRawFromSource, createSourceFromRaw } from "./util/createSource"; import { createFakeCompilationDependencies, - createFakeProcessAssetsHook + createFakeProcessAssetsHook, + createProcessAssetsHook } from "./util/fake"; import { NormalizedJsModule, normalizeJsModule } from "./util/normalization"; import MergeCaller from "./util/MergeCaller"; @@ -85,11 +86,12 @@ export class Compilation { hooks: { processAssets: ReturnType; log: tapable.SyncBailHook<[string, LogEntry], true>; - additionalAssets: tapable.AsyncSeriesHook< - Assets, - tapable.UnsetAdditionalOptions - >; + additionalAssets: any; optimizeModules: tapable.SyncBailHook, undefined>; + optimizeTree: tapable.AsyncSeriesBailHook< + [Iterable, Iterable], + undefined + >; optimizeChunkModules: tapable.AsyncSeriesBailHook< [Iterable, Iterable], undefined @@ -116,6 +118,12 @@ export class Compilation { normalModuleFactory?: NormalModuleFactory; children: Compilation[] = []; contextModuleFactory?: ContextModuleFactory; + fileSystemInfo = { + createSnapshot() { + // fake implement to support html-webpack-plugin + return null; + } + }; constructor(compiler: Compiler, inner: JsCompilation) { this.name = undefined; @@ -126,9 +134,15 @@ export class Compilation { processAssets: processAssetsHooks, // TODO: webpack 6 deprecate, keep it just for compatibility /** @deprecated */ - additionalAssets: processAssetsHooks.stageAdditional, + additionalAssets: createProcessAssetsHook( + processAssetsHooks, + "additionalAssets", + Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL, + () => [] + ), log: new tapable.SyncBailHook(["origin", "logEntry"]), optimizeModules: new tapable.SyncBailHook(["modules"]), + optimizeTree: new tapable.AsyncSeriesBailHook(["chunks", "modules"]), optimizeChunkModules: new tapable.AsyncSeriesBailHook([ "chunks", "modules" @@ -444,15 +458,25 @@ export class Compilation { get errors() { let inner = this.#inner; return { - push: (...errs: (Error | JsStatsError)[]) => { + push: (...errs: (Error | JsStatsError | string)[]) => { // compatible for javascript array for (let i = 0; i < errs.length; i++) { let error = errs[i]; - this.#inner.pushDiagnostic( - "error", - isJsStatsError(error) ? error.title : error.name, - concatErrorMsgAndStack(error) - ); + if (isJsStatsError(error)) { + this.#inner.pushDiagnostic( + "error", + error.title, + concatErrorMsgAndStack(error) + ); + } else if (typeof error === "string") { + this.#inner.pushDiagnostic("error", "Error", error); + } else { + this.#inner.pushDiagnostic( + "error", + error.name, + concatErrorMsgAndStack(error) + ); + } } }, [Symbol.iterator]() { diff --git a/packages/rspack/src/Compiler.ts b/packages/rspack/src/Compiler.ts index 84e9ebdf3c0..87bd3ef8560 100644 --- a/packages/rspack/src/Compiler.ts +++ b/packages/rspack/src/Compiler.ts @@ -42,26 +42,11 @@ import Watching from "./Watching"; import { NormalModule } from "./NormalModule"; import { normalizeJsModule } from "./util/normalization"; import { - ElectronTargetPlugin, - ExternalsPlugin, - HttpExternalsRspackPlugin, - NodeTargetPlugin, RspackBuiltinPlugin, deprecated_resolveBuiltins } from "./builtin-plugin"; -import assert from "assert"; -import EntryOptionPlugin from "./lib/EntryOptionPlugin"; +import { optionsApply_compat } from "./rspackOptionsApply"; -class NodeTemplatePlugin { - apply() {} -} - -class EnableLibraryPlugin { - constructor(private libraryType: string) {} - apply(compiler: Compiler) { - compiler.options.output.enabledLibraryTypes = [this.libraryType]; - } -} class HotModuleReplacementPlugin { apply() {} } @@ -168,21 +153,36 @@ class Compiler { get ExternalsPlugin() { return require("./builtin-plugin").ExternalsPlugin; }, + get LoaderOptionsPlugin() { + return require("./lib/LoaderOptionsPlugin").LoaderOptionsPlugin; + }, + get LoaderTargetPlugin() { + return require("./lib/LoaderTargetPlugin").LoaderTargetPlugin; + }, WebpackError: Error, ModuleFilenameHelpers, node: { get NodeTargetPlugin() { return require("./builtin-plugin").NodeTargetPlugin; }, - NodeTemplatePlugin + get NodeTemplatePlugin() { + return require("./node/NodeTemplatePlugin").default; + } }, electron: { get ElectronTargetPlugin() { return require("./builtin-plugin").ElectronTargetPlugin; } }, + wasm: { + get EnableWasmLoadingPlugin() { + return require("./builtin-plugin").EnableWasmLoadingPlugin; + } + }, library: { - EnableLibraryPlugin + get EnableLibraryPlugin() { + return require("./builtin-plugin").EnableLibraryPlugin; + } }, util: { get createHash() { @@ -306,45 +306,7 @@ class Compiler { const options = this.options; // TODO: remove this in v0.4 - if (this.parentCompilation === undefined) { - if (options.externals) { - assert( - options.externalsType, - "options.externalsType should have value after `applyRspackOptionsDefaults`" - ); - new ExternalsPlugin(options.externalsType, options.externals).apply( - this - ); - } - - if (options.externalsPresets.node) { - new NodeTargetPlugin().apply(this); - } - if (options.externalsPresets.electronMain) { - new ElectronTargetPlugin("main").apply(this); - } - if (options.externalsPresets.electronPreload) { - new ElectronTargetPlugin("preload").apply(this); - } - if (options.externalsPresets.electronRenderer) { - new ElectronTargetPlugin("renderer").apply(this); - } - if ( - options.externalsPresets.electron && - !options.externalsPresets.electronMain && - !options.externalsPresets.electronPreload && - !options.externalsPresets.electronRenderer - ) { - new ElectronTargetPlugin().apply(this); - } - if ( - options.externalsPresets.web || - (options.externalsPresets.node && options.experiments.css) - ) { - new HttpExternalsRspackPlugin(!!options.experiments.css).apply(this); - } - EntryOptionPlugin.applyEntryOption(this, this.context, options.entry); - } + optionsApply_compat(this, options); // TODO: remove this when drop support for builtins options options.builtins = deprecated_resolveBuiltins( options.builtins, @@ -440,6 +402,7 @@ class Compiler { // No matter how it will be implemented, it will be copied to the child compiler. compilation: this.#compilation.bind(this), optimizeModules: this.#optimizeModules.bind(this), + optimizeTree: this.#optimizeTree.bind(this), optimizeChunkModule: this.#optimizeChunkModules.bind(this), finishModules: this.#finishModules.bind(this), normalModuleFactoryResolveForScheme: @@ -873,6 +836,15 @@ class Compiler { ); this.#updateDisabledHooks(); } + + async #optimizeTree() { + await this.compilation.hooks.optimizeTree.promise( + this.compilation.__internal__getChunks(), + this.compilation.modules + ); + this.#updateDisabledHooks(); + } + async #optimizeModules() { await this.compilation.hooks.optimizeModules.promise( this.compilation.modules diff --git a/packages/rspack/src/builtin-plugin/ArrayPushCallbackChunkFormatPlugin.ts b/packages/rspack/src/builtin-plugin/ArrayPushCallbackChunkFormatPlugin.ts new file mode 100644 index 00000000000..11950cd8a77 --- /dev/null +++ b/packages/rspack/src/builtin-plugin/ArrayPushCallbackChunkFormatPlugin.ts @@ -0,0 +1,6 @@ +import { BuiltinPluginName, create } from "./base"; + +export const ArrayPushCallbackChunkFormatPlugin = create( + BuiltinPluginName.ArrayPushCallbackChunkFormatPlugin, + () => {} +); diff --git a/packages/rspack/src/builtin-plugin/CommonJsChunkFormatPlugin.ts b/packages/rspack/src/builtin-plugin/CommonJsChunkFormatPlugin.ts new file mode 100644 index 00000000000..57e73be6452 --- /dev/null +++ b/packages/rspack/src/builtin-plugin/CommonJsChunkFormatPlugin.ts @@ -0,0 +1,6 @@ +import { BuiltinPluginName, create } from "./base"; + +export const CommonJsChunkFormatPlugin = create( + BuiltinPluginName.CommonJsChunkFormatPlugin, + () => {} +); diff --git a/packages/rspack/src/builtin-plugin/EnableChunkLoadingPlugin.ts b/packages/rspack/src/builtin-plugin/EnableChunkLoadingPlugin.ts new file mode 100644 index 00000000000..f035133ebbd --- /dev/null +++ b/packages/rspack/src/builtin-plugin/EnableChunkLoadingPlugin.ts @@ -0,0 +1,6 @@ +import { BuiltinPluginName, create } from "./base"; + +export const EnableChunkLoadingPlugin = create( + BuiltinPluginName.EnableChunkLoadingPlugin, + type => type +); diff --git a/packages/rspack/src/builtin-plugin/EnableLibraryPlugin.ts b/packages/rspack/src/builtin-plugin/EnableLibraryPlugin.ts new file mode 100644 index 00000000000..6a553f2dfc5 --- /dev/null +++ b/packages/rspack/src/builtin-plugin/EnableLibraryPlugin.ts @@ -0,0 +1,6 @@ +import { BuiltinPluginName, create } from "./base"; + +export const EnableLibraryPlugin = create( + BuiltinPluginName.EnableLibraryPlugin, + type => type +); diff --git a/packages/rspack/src/builtin-plugin/EnableWasmLoadingPlugin.ts b/packages/rspack/src/builtin-plugin/EnableWasmLoadingPlugin.ts new file mode 100644 index 00000000000..2a07374a1bf --- /dev/null +++ b/packages/rspack/src/builtin-plugin/EnableWasmLoadingPlugin.ts @@ -0,0 +1,6 @@ +import { BuiltinPluginName, create } from "./base"; + +export const EnableWasmLoadingPlugin = create( + BuiltinPluginName.EnableWasmLoadingPlugin, + type => type +); diff --git a/packages/rspack/src/builtin-plugin/EntryPlugin.ts b/packages/rspack/src/builtin-plugin/EntryPlugin.ts index 41cfd6388d0..f05914fdea7 100644 --- a/packages/rspack/src/builtin-plugin/EntryPlugin.ts +++ b/packages/rspack/src/builtin-plugin/EntryPlugin.ts @@ -16,12 +16,14 @@ export const EntryPlugin = create( ( context: string, entry: string, - options: EntryOptions + options: EntryOptions | string = "" ): RawEntryPluginOptions => { + let entryOptions = + typeof options === "string" ? { name: options } : options; return { context, entry, - options: getRawEntryOptions(options) + options: getRawEntryOptions(entryOptions) }; } ); diff --git a/packages/rspack/src/builtin-plugin/ModuleChunkFormatPlugin.ts b/packages/rspack/src/builtin-plugin/ModuleChunkFormatPlugin.ts new file mode 100644 index 00000000000..27f77401584 --- /dev/null +++ b/packages/rspack/src/builtin-plugin/ModuleChunkFormatPlugin.ts @@ -0,0 +1,6 @@ +import { BuiltinPluginName, create } from "./base"; + +export const ModuleChunkFormatPlugin = create( + BuiltinPluginName.ModuleChunkFormatPlugin, + () => {} +); diff --git a/packages/rspack/src/builtin-plugin/base.ts b/packages/rspack/src/builtin-plugin/base.ts index 4e79e457f4a..f35a52e4db7 100644 --- a/packages/rspack/src/builtin-plugin/base.ts +++ b/packages/rspack/src/builtin-plugin/base.ts @@ -11,6 +11,12 @@ export enum BuiltinPluginName { ExternalsPlugin = "ExternalsPlugin", NodeTargetPlugin = "NodeTargetPlugin", ElectronTargetPlugin = "ElectronTargetPlugin", + EnableChunkLoadingPlugin = "EnableChunkLoadingPlugin", + EnableLibraryPlugin = "EnableLibraryPlugin", + EnableWasmLoadingPlugin = "EnableWasmLoadingPlugin", + CommonJsChunkFormatPlugin = "CommonJsChunkFormatPlugin", + ArrayPushCallbackChunkFormatPlugin = "ArrayPushCallbackChunkFormatPlugin", + ModuleChunkFormatPlugin = "ModuleChunkFormatPlugin", HttpExternalsRspackPlugin = "HttpExternalsRspackPlugin", CopyRspackPlugin = "CopyRspackPlugin", HtmlRspackPlugin = "HtmlRspackPlugin", diff --git a/packages/rspack/src/builtin-plugin/index.ts b/packages/rspack/src/builtin-plugin/index.ts index 3cc0b6b8e97..1410836b217 100644 --- a/packages/rspack/src/builtin-plugin/index.ts +++ b/packages/rspack/src/builtin-plugin/index.ts @@ -9,6 +9,12 @@ export * from "./ExternalsPlugin"; export * from "./NodeTargetPlugin"; export * from "./ElectronTargetPlugin"; export * from "./HttpExternalsRspackPlugin"; +export * from "./EnableChunkLoadingPlugin"; +export * from "./EnableLibraryPlugin"; +export * from "./EnableWasmLoadingPlugin"; +export * from "./ArrayPushCallbackChunkFormatPlugin"; +export * from "./CommonJsChunkFormatPlugin"; +export * from "./ModuleChunkFormatPlugin"; export * from "./HtmlRspackPlugin"; export * from "./CopyRspackPlugin"; diff --git a/packages/rspack/src/config/adapter.ts b/packages/rspack/src/config/adapter.ts index fa2e7ad9cb8..f0b89d783b3 100644 --- a/packages/rspack/src/config/adapter.ts +++ b/packages/rspack/src/config/adapter.ts @@ -180,7 +180,6 @@ function getRawOutput(output: OutputNormalized): RawOptions["output"] { clean: output.clean!, assetModuleFilename: output.assetModuleFilename!, filename: output.filename!, - chunkFormat: output.chunkFormat === false ? "false" : output.chunkFormat!, chunkFilename: output.chunkFilename!, chunkLoading: chunkLoading === false ? "false" : chunkLoading, crossOriginLoading: getRawCrossOriginLoading(output.crossOriginLoading!), diff --git a/packages/rspack/src/index.ts b/packages/rspack/src/index.ts index 892044d1906..c79f068792f 100644 --- a/packages/rspack/src/index.ts +++ b/packages/rspack/src/index.ts @@ -12,6 +12,7 @@ export * from "./NormalModuleFactory"; export { cachedCleverMerge as cleverMerge } from "./util/cleverMerge"; export { EnvironmentPlugin } from "./lib/EnvironmentPlugin"; export { LoaderOptionsPlugin } from "./lib/LoaderOptionsPlugin"; +export { LoaderTargetPlugin } from "./lib/LoaderTargetPlugin"; export { registerGlobalTrace as experimental_registerGlobalTrace, cleanupGlobalTrace as experimental_cleanupGlobalTrace @@ -31,7 +32,8 @@ export { SwcCssMinimizerRspackPlugin, CopyRspackPlugin, EntryPlugin, - ExternalsPlugin + ExternalsPlugin, + EnableChunkLoadingPlugin } from "./builtin-plugin"; export type { BannerPluginArgument, @@ -43,8 +45,18 @@ export type { CopyRspackPluginOptions, EntryOptions } from "./builtin-plugin"; -import { ElectronTargetPlugin, NodeTargetPlugin } from "./builtin-plugin"; -export const node = { NodeTargetPlugin }; + +import NodeTemplatePlugin from "./node/NodeTemplatePlugin"; +import { NodeTargetPlugin } from "./builtin-plugin"; +export const node = { NodeTargetPlugin, NodeTemplatePlugin }; + +import { ElectronTargetPlugin } from "./builtin-plugin"; export const electron = { ElectronTargetPlugin }; +import { EnableLibraryPlugin } from "./builtin-plugin"; +export const library = { EnableLibraryPlugin }; + +import { EnableWasmLoadingPlugin } from "./builtin-plugin"; +export const wasm = { EnableWasmLoadingPlugin }; + export { Watching }; diff --git a/packages/rspack/src/lib/LoaderTargetPlugin.js b/packages/rspack/src/lib/LoaderTargetPlugin.js new file mode 100644 index 00000000000..7156e5fa4c9 --- /dev/null +++ b/packages/rspack/src/lib/LoaderTargetPlugin.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const NormalModule = require("../NormalModule"); + +/** @typedef {import("./Compiler")} Compiler */ + +class LoaderTargetPlugin { + /** + * @param {string} target the target + */ + constructor(target) { + this.target = target; + } + + /** + * Apply the plugin + * @param {Compiler} compiler the compiler instance + * @returns {void} + */ + apply(compiler) { + compiler.hooks.compilation.tap("LoaderTargetPlugin", compilation => { + NormalModule.getCompilationHooks(compilation).loader.tap( + "LoaderTargetPlugin", + loaderContext => { + loaderContext.target = this.target; + } + ); + }); + } +} + +export { LoaderTargetPlugin }; diff --git a/packages/rspack/src/node/NodeTemplatePlugin.ts b/packages/rspack/src/node/NodeTemplatePlugin.ts new file mode 100644 index 00000000000..c9f64bb7653 --- /dev/null +++ b/packages/rspack/src/node/NodeTemplatePlugin.ts @@ -0,0 +1,30 @@ +/** + * The following code is modified based on + * https://github.com/webpack/webpack/blob/4b4ca3b/lib/node/NodeTemplatePlugin.js + * + * MIT Licensed + * Author Tobias Koppers @sokra + * Copyright (c) JS Foundation and other contributors + * https://github.com/webpack/webpack/blob/main/LICENSE + */ + +import { Compiler } from "../Compiler"; +import { + CommonJsChunkFormatPlugin, + EnableChunkLoadingPlugin +} from "../builtin-plugin"; + +export type NodeTemplatePluginOptions = { asyncChunkLoading?: boolean }; + +export default class NodeTemplatePlugin { + constructor(private _options: NodeTemplatePluginOptions = {}) {} + + apply(compiler: Compiler) { + const chunkLoading = this._options.asyncChunkLoading + ? "async-node" + : "require"; + compiler.options.output.chunkLoading = chunkLoading; + new CommonJsChunkFormatPlugin().apply(compiler); + new EnableChunkLoadingPlugin(chunkLoading).apply(compiler); + } +} diff --git a/packages/rspack/src/rspackOptionsApply.ts b/packages/rspack/src/rspackOptionsApply.ts index 73486506501..afb4cb351b0 100644 --- a/packages/rspack/src/rspackOptionsApply.ts +++ b/packages/rspack/src/rspackOptionsApply.ts @@ -21,6 +21,118 @@ import { DefaultStatsPrinterPlugin } from "./stats/DefaultStatsPrinterPlugin"; import { cleverMerge } from "./util/cleverMerge"; import assert from "assert"; import IgnoreWarningsPlugin from "./lib/ignoreWarningsPlugin"; +import EntryOptionPlugin from "./lib/EntryOptionPlugin"; +import { + ArrayPushCallbackChunkFormatPlugin, + CommonJsChunkFormatPlugin, + ElectronTargetPlugin, + EnableChunkLoadingPlugin, + EnableLibraryPlugin, + EnableWasmLoadingPlugin, + ExternalsPlugin, + HttpExternalsRspackPlugin, + ModuleChunkFormatPlugin, + NodeTargetPlugin +} from "./builtin-plugin"; + +export function optionsApply_compat( + compiler: Compiler, + options: RspackOptionsNormalized +) { + if (compiler.parentCompilation === undefined) { + if (options.externals) { + assert( + options.externalsType, + "options.externalsType should have value after `applyRspackOptionsDefaults`" + ); + new ExternalsPlugin(options.externalsType, options.externals).apply( + compiler + ); + } + + if (options.externalsPresets.node) { + new NodeTargetPlugin().apply(compiler); + } + if (options.externalsPresets.electronMain) { + new ElectronTargetPlugin("main").apply(compiler); + } + if (options.externalsPresets.electronPreload) { + new ElectronTargetPlugin("preload").apply(compiler); + } + if (options.externalsPresets.electronRenderer) { + new ElectronTargetPlugin("renderer").apply(compiler); + } + if ( + options.externalsPresets.electron && + !options.externalsPresets.electronMain && + !options.externalsPresets.electronPreload && + !options.externalsPresets.electronRenderer + ) { + new ElectronTargetPlugin().apply(compiler); + } + if ( + options.externalsPresets.web || + (options.externalsPresets.node && options.experiments.css) + ) { + new HttpExternalsRspackPlugin(!!options.experiments.css).apply(compiler); + } + + if (typeof options.output.chunkFormat === "string") { + switch (options.output.chunkFormat) { + case "array-push": { + new ArrayPushCallbackChunkFormatPlugin().apply(compiler); + break; + } + case "commonjs": { + new CommonJsChunkFormatPlugin().apply(compiler); + break; + } + case "module": { + new ModuleChunkFormatPlugin().apply(compiler); + break; + } + default: + throw new Error( + "Unsupported chunk format '" + options.output.chunkFormat + "'." + ); + } + } + + if ( + options.output.enabledChunkLoadingTypes && + options.output.enabledChunkLoadingTypes.length > 0 + ) { + for (const type of options.output.enabledChunkLoadingTypes) { + new EnableChunkLoadingPlugin(type).apply(compiler); + } + } + + if ( + options.output.enabledWasmLoadingTypes && + options.output.enabledWasmLoadingTypes.length > 0 + ) { + for (const type of options.output.enabledWasmLoadingTypes) { + new EnableWasmLoadingPlugin(type).apply(compiler); + } + } + + if ( + options.output.enabledLibraryTypes && + options.output.enabledLibraryTypes.length > 0 + ) { + for (const type of options.output.enabledLibraryTypes) { + new EnableLibraryPlugin(type).apply(compiler); + } + } + + // TODO: change to new EntryOptionPlugin().apply(compiler); + EntryOptionPlugin.applyEntryOption( + compiler, + compiler.context, + options.entry + ); + } +} export class RspackOptionsApply { constructor() {} @@ -33,43 +145,6 @@ export class RspackOptionsApply { compiler.name = options.name; compiler.outputFileSystem = fs; - // if (options.externals) { - // assert( - // options.externalsType, - // "options.externalsType should have value after `applyRspackOptionsDefaults`" - // ); - // new ExternalsPlugin(options.externalsType, options.externals).apply( - // compiler - // ); - // } - - // if (options.externalsPresets.node) { - // new NodeTargetPlugin().apply(compiler); - // } - // if (options.externalsPresets.electronMain) { - // new ElectronTargetPlugin("main").apply(compiler); - // } - // if (options.externalsPresets.electronPreload) { - // new ElectronTargetPlugin("preload").apply(compiler); - // } - // if (options.externalsPresets.electronRenderer) { - // new ElectronTargetPlugin("renderer").apply(compiler); - // } - // if ( - // options.externalsPresets.electron && - // !options.externalsPresets.electronMain && - // !options.externalsPresets.electronPreload && - // !options.externalsPresets.electronRenderer - // ) { - // new ElectronTargetPlugin().apply(compiler); - // } - // if ( - // options.externalsPresets.web || - // (options.externalsPresets.node && options.experiments.css) - // ) { - // new HttpExternalsPlugin(!!options.experiments.css).apply(compiler); - // } - const runtimeChunk = options.optimization .runtimeChunk as OptimizationRuntimeChunkNormalized; if (runtimeChunk) { diff --git a/packages/rspack/src/util/fake.ts b/packages/rspack/src/util/fake.ts index 1ba2a259697..d8486f63ce9 100644 --- a/packages/rspack/src/util/fake.ts +++ b/packages/rspack/src/util/fake.ts @@ -49,6 +49,58 @@ export const createFakeProcessAssetsHook = (compilation: Compilation) => { }; }; +export type FakeHook = T & { _fakeHook: true }; + +export const createFakeHook = (fakeHook: T): FakeHook => { + return Object.freeze(Object.assign(fakeHook, { _fakeHook: true as const })); +}; + +export const createProcessAssetsHook = ( + processAssetsHooks: ReturnType, + name: string, + stage: number, + getArgs: () => tapable.AsArray +): FakeHook< + Pick, "tap" | "tapAsync" | "tapPromise" | "name"> +> => { + const errorMessage = ( + reason: string + ) => `Can't automatically convert plugin using Compilation.hooks.${name} to Compilation.hooks.processAssets because ${reason}. +BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a single Compilation.hooks.processAssets hook.`; + const getOptions = ( + options: string | (tapable.TapOptions & { name: string }) + ) => { + if (typeof options === "string") options = { name: options }; + if (options.stage) { + throw new Error(errorMessage("it's using the 'stage' option")); + } + return { ...options, stage: stage }; + }; + const tap: tapable.AsyncSeriesHook["tap"] = (options, fn) => { + processAssetsHooks.tap(getOptions(options), () => fn(...getArgs())); + }; + const tapAsync: tapable.AsyncSeriesHook["tapAsync"] = (options, fn) => { + processAssetsHooks.tapAsync(getOptions(options), (assets, callback) => + (fn as any)(...getArgs(), callback) + ); + }; + const tapPromise: tapable.AsyncSeriesHook["tapPromise"] = ( + options, + fn + ) => { + processAssetsHooks.tapPromise(getOptions(options), () => fn(...getArgs())); + }; + return createFakeHook({ + name, + intercept() { + throw new Error(errorMessage("it's using 'intercept'")); + }, + tap, + tapAsync, + tapPromise + }); +}; + export function createFakeCompilationDependencies( getDeps: () => string[], addDeps: (deps: string[]) => void diff --git a/packages/rspack/tests/ConfigCase.template.ts b/packages/rspack/tests/ConfigCase.template.ts index 4cc23fa0d54..54ef2fdae3e 100644 --- a/packages/rspack/tests/ConfigCase.template.ts +++ b/packages/rspack/tests/ConfigCase.template.ts @@ -538,13 +538,7 @@ export const describeCases = config => { __dirname: path.dirname(p), __filename: p, _globalAssign: { expect }, - define, - // TODO support __non_webpack_require__ - __non_webpack_require__: _require.bind( - null, - path.dirname(p), - options - ) + define }; if (testConfig.moduleScope) { testConfig.moduleScope(moduleScope); diff --git a/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap b/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap index 788ecedacb1..f6c1b02346c 100644 --- a/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap +++ b/packages/rspack/tests/__snapshots__/StatsTestCases.test.ts.snap @@ -500,7 +500,7 @@ exports[`StatsTestCases should print correct stats for filename 1`] = ` "errors": [], "errorsCount": 0, "filteredModules": undefined, - "hash": "426fdcc9ed1638dfcbc9", + "hash": "6d7c52e50cefca7d30c4", "logging": {}, "modules": [ { @@ -602,7 +602,7 @@ chunk {main} main.xxxx.js (main) >{dynamic_js}< [entry] entry ./index ./dynamic.js [426] {dynamic_js} dynamic import ./dynamic [10] -rspack compiled successfully (426fdcc9ed1638dfcbc9)" +rspack compiled successfully (6d7c52e50cefca7d30c4)" `; exports[`StatsTestCases should print correct stats for hot+production 1`] = ` diff --git a/packages/rspack/tests/configCases/plugins/html-webpack-plugin/index.js b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/index.js new file mode 100644 index 00000000000..0779acb3c1a --- /dev/null +++ b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/index.js @@ -0,0 +1,15 @@ +const fs = require("fs"); +const path = require("path"); + +it("html-webpack-plugin + html-loader", () => { + const pugDist = fs.readFileSync( + path.resolve(__dirname, "pug-index.html"), + "utf-8" + ); + expect(pugDist).toContain("Pug Template"); + const htmlDist = fs.readFileSync( + path.resolve(__dirname, "html-index.html"), + "utf-8" + ); + expect(htmlDist).toContain("Html Template"); +}); diff --git a/packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.html b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.html new file mode 100644 index 00000000000..88b15d82528 --- /dev/null +++ b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.html @@ -0,0 +1,10 @@ + + + + + Html Template + + + + + diff --git a/packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.pug b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.pug new file mode 100644 index 00000000000..bb551621b77 --- /dev/null +++ b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/template.pug @@ -0,0 +1,9 @@ +doctype html +html + head + meta(charset="utf-8") + title Pug Template + body + p Some unique text + each jsFile in htmlWebpackPlugin.files.js + script(src!=jsFile) diff --git a/packages/rspack/tests/configCases/plugins/html-webpack-plugin/webpack.config.js b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/webpack.config.js new file mode 100644 index 00000000000..8b4819b5945 --- /dev/null +++ b/packages/rspack/tests/configCases/plugins/html-webpack-plugin/webpack.config.js @@ -0,0 +1,21 @@ +const path = require("path"); +const HtmlPlugin = require("html-webpack-plugin"); + +module.exports = [ + { + plugins: [ + new HtmlPlugin({ + filename: "html-index.html", + template: "html-loader!" + path.join(__dirname, "template.html") + }) + ] + }, + { + plugins: [ + new HtmlPlugin({ + filename: "pug-index.html", + template: "pug-loader!" + path.join(__dirname, "template.pug") + }) + ] + } +]; diff --git a/packages/rspack/tests/runtimeCases/runtime/split-css-chunk-async/webpack.config.js b/packages/rspack/tests/runtimeCases/runtime/split-css-chunk-async/webpack.config.js index c45ae6cace9..74aeb5c088c 100644 --- a/packages/rspack/tests/runtimeCases/runtime/split-css-chunk-async/webpack.config.js +++ b/packages/rspack/tests/runtimeCases/runtime/split-css-chunk-async/webpack.config.js @@ -1,29 +1,29 @@ module.exports = { entry: { - main: './index1.js', - main2: './index2.js', - main3: './index3.js' + main: "./index1.js", + main2: "./index2.js", + main3: "./index3.js" }, output: { - chunkFilename: '[id].[contenthash].js' + chunkFilename: "[id].[contenthash].js" }, optimization: { splitChunks: { cacheGroups: { common: { - chunks: 'all', + chunks: "all", test: /common/, enforce: true, - name: 'common' + name: "common" }, share: { - chunks: 'all', + chunks: "all", test: /share/, enforce: true, - name: 'share' + name: "share" } } }, - runtimeChunk: 'single' + runtimeChunk: "single" } -} +}; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 98e19cce8ee..18be97aeb29 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -470,22 +470,22 @@ importers: examples/plugin-compat: specifiers: '@rspack/cli': workspace:* - '@rspack/plugin-html': workspace:* '@rspack/plugin-minify': workspace:* copy-webpack-plugin: 5.1.2 fork-ts-checker-webpack-plugin: 8.0.0 generate-package-json-webpack-plugin: ^2.6.0 + html-webpack-plugin: ^5.5.0 license-webpack-plugin: ^4.0.2 rspack-manifest-plugin: 5.0.0-alpha0 webpack-bundle-analyzer: 4.7.0 webpack-stats-plugin: 1.1.1 devDependencies: '@rspack/cli': link:../../packages/rspack-cli - '@rspack/plugin-html': link:../../packages/rspack-plugin-html '@rspack/plugin-minify': link:../../packages/rspack-plugin-minify copy-webpack-plugin: 5.1.2 fork-ts-checker-webpack-plugin: 8.0.0 generate-package-json-webpack-plugin: 2.6.0 + html-webpack-plugin: 5.5.0 license-webpack-plugin: 4.0.2 rspack-manifest-plugin: 5.0.0-alpha0 webpack-bundle-analyzer: 4.7.0 @@ -926,12 +926,15 @@ importers: enhanced-resolve: 5.12.0 file-loader: ^6.2.0 graceful-fs: 4.2.10 + html-loader: ^4.2.0 + html-webpack-plugin: ^5.5.0 jest-serializer-path: ^0.1.15 less: 4.1.3 less-loader: ^11.1.0 neo-async: 2.6.2 postcss-loader: ^7.0.2 postcss-pxtorem: ^6.0.0 + pug-loader: ^2.4.0 react-refresh: 0.14.0 react-relay: ^14.1.0 sass: ^1.56.2 @@ -977,11 +980,14 @@ importers: copy-webpack-plugin: 5.1.2 cross-env: 7.0.3 file-loader: 6.2.0 + html-loader: 4.2.0 + html-webpack-plugin: 5.5.0 jest-serializer-path: 0.1.15 less: 4.1.3 less-loader: 11.1.0_less@4.1.3 postcss-loader: 7.0.2 postcss-pxtorem: 6.0.0 + pug-loader: 2.4.0 react-relay: 14.1.0 sass: 1.56.2 sass-loader: 13.2.0_sass@1.56.2 @@ -12053,7 +12059,6 @@ packages: dependencies: webpack: 5.76.0_webpack-cli@4.10.0 webpack-cli: 4.10.0_webpack@5.76.0 - dev: true /@webpack-cli/info/1.5.0_webpack-cli@4.10.0: resolution: {integrity: sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==} @@ -12062,7 +12067,6 @@ packages: dependencies: envinfo: 7.8.1 webpack-cli: 4.10.0_webpack@5.76.0 - dev: true /@webpack-cli/serve/1.7.0_webpack-cli@4.10.0: resolution: {integrity: sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==} @@ -12074,7 +12078,6 @@ packages: optional: true dependencies: webpack-cli: 4.10.0_webpack@5.76.0 - dev: true /@xtuc/ieee754/1.2.0: resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==} @@ -13985,7 +13988,6 @@ packages: is-plain-object: 2.0.4 kind-of: 6.0.3 shallow-clone: 3.0.1 - dev: true /clone-response/1.0.2: resolution: {integrity: sha512-yjLXh88P599UOyPTFX0POsd7WxnbsVsGohcwzHOLspIhhpalPw1BcqED8NblyZLKcGrL8dTgMlcaZxV2jAD41Q==} @@ -15773,7 +15775,6 @@ packages: resolution: {integrity: sha512-/o+BXHmB7ocbHEAs6F2EnG0ogybVVUdkRunTT2glZU9XAaGmhqskrvKwqXuDfNjEO0LZKWdejEEpnq8aM0tOaw==} engines: {node: '>=4'} hasBin: true - dev: true /err-code/2.0.3: resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==} @@ -16478,7 +16479,6 @@ packages: /fastest-levenshtein/1.0.16: resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} engines: {node: '>= 4.9.1'} - dev: true /fastq/1.13.0: resolution: {integrity: sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==} @@ -18113,7 +18113,6 @@ packages: dependencies: pkg-dir: 4.2.0 resolve-cwd: 3.0.0 - dev: true /imurmurhash/0.1.4: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} @@ -18251,7 +18250,6 @@ packages: /interpret/2.2.0: resolution: {integrity: sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==} engines: {node: '>= 0.10'} - dev: true /interpret/3.1.1: resolution: {integrity: sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==} @@ -18613,7 +18611,6 @@ packages: engines: {node: '>=0.10.0'} dependencies: isobject: 3.0.1 - dev: true /is-plain-object/5.0.0: resolution: {integrity: sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==} @@ -18804,7 +18801,6 @@ packages: /isobject/3.0.1: resolution: {integrity: sha512-WhB9zCku7EGTj/HQQRz5aUQEUeoQZH2bWcltRErOpymJ4boYE6wL9Tbr23krRPSZ+C5zqNSrSw+Cc7sZZ4b7vg==} engines: {node: '>=0.10.0'} - dev: true /isomorphic-fetch/2.2.1: resolution: {integrity: sha512-9c4TNAKYXM5PRyVcwUZrF3W09nQ+sO7+jydgs4ZGW9dhsLG2VOlISJABombdQqQRXCwuYG3sYV/puGf5rp0qmA==} @@ -19586,7 +19582,7 @@ packages: dependencies: universalify: 2.0.0 optionalDependencies: - graceful-fs: 4.2.10 + graceful-fs: 4.2.11 /jsonparse/1.3.1: resolution: {integrity: sha512-POQXvpdL69+CluYsillJ7SUhKvytYjW9vG/GKpnf+xP8UWgYEM/RaMzHHofbALDiKbbP1W8UEYmgGl39WkPZsg==} @@ -19715,7 +19711,6 @@ packages: /kind-of/6.0.3: resolution: {integrity: sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==} engines: {node: '>=0.10.0'} - dev: true /kleur/3.0.3: resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} @@ -23738,7 +23733,6 @@ packages: engines: {node: '>= 0.10'} dependencies: resolve: 1.22.2 - dev: true /rechoir/0.8.0: resolution: {integrity: sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==} @@ -24025,7 +24019,6 @@ packages: engines: {node: '>=8'} dependencies: resolve-from: 5.0.0 - dev: true /resolve-from/4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} @@ -24034,7 +24027,6 @@ packages: /resolve-from/5.0.0: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} - dev: true /resolve-pathname/3.0.0: resolution: {integrity: sha512-C7rARubxI8bXFNB/hqcp/4iUeIXJhJZvFPFPiSPRnhU5UPxzMFIl+2E6yY6c4k9giDJAhtV+enfA+G89N6Csng==} @@ -24739,7 +24731,6 @@ packages: engines: {node: '>=8'} dependencies: kind-of: 6.0.3 - dev: true /shallowequal/1.1.0: resolution: {integrity: sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==} @@ -26243,7 +26234,7 @@ packages: schema-utils: 3.1.2 serialize-javascript: 6.0.1 terser: 5.17.1 - webpack: 5.76.0 + webpack: 5.76.0_webpack-cli@4.10.0 /terser/5.16.1: resolution: {integrity: sha512-xvQfyfA1ayT0qdK47zskQgRZeWLoOQ8JQ6mIgRGVNwZKdQMU+5FkCBjmv4QjcrTzyZquRw2FVtlJSRUmMKQslw==} @@ -27697,7 +27688,6 @@ packages: rechoir: 0.7.1 webpack: 5.76.0_webpack-cli@4.10.0 webpack-merge: 5.9.0 - dev: true /webpack-dev-middleware/5.3.3: resolution: {integrity: sha512-hj5CYrY0bZLB+eTO+x/j67Pkrquiy7kWepMHmUMoPsmcUaeEnQJqFzHJOyxgWlq746/wUuA64p9ta34Kyb01pA==} @@ -27972,7 +27962,6 @@ packages: dependencies: clone-deep: 4.0.1 wildcard: 2.0.0 - dev: true /webpack-sources/2.3.1: resolution: {integrity: sha512-y9EI9AO42JjEcrTJFOYmVywVZdKVUfOvDUPsJea5GIr1JOEGFVqwlY2K098fFoIjOkDzHn2AjRvM8dsBZu+gCA==} @@ -28087,7 +28076,6 @@ packages: - '@swc/core' - esbuild - uglify-js - dev: true /webpack/5.80.0_esbuild@0.17.18: resolution: {integrity: sha512-OIMiq37XK1rWO8mH9ssfFKZsXg4n6klTEDL7S8/HqbAOBBaiy8ABvXvz0dDCXeEF9gqwxSvVk611zFPjS8hJxA==} @@ -28255,7 +28243,6 @@ packages: /wildcard/2.0.0: resolution: {integrity: sha512-JcKqAHLPxcdb9KM49dufGXn2x3ssnfjbcaQdLlfZsL9rH9wgDQjUtDxbo8NE0F6SFvydeu1VhZe7hZuHsB2/pw==} - dev: true /window-size/0.1.0: resolution: {integrity: sha512-1pTPQDKTdd61ozlKGNCjhNRd+KPmgLSGa3mZTHoOliaGcESD8G1PXhh7c1fgiPjVbNVfgy2Faw4BI8/m0cC8Mg==} diff --git a/webpack-test/configCases/asset-modules/base-uri/test.filter.js b/webpack-test/configCases/asset-modules/base-uri/test.filter.js index 3be456dcd23..4108ffb37d9 100644 --- a/webpack-test/configCases/asset-modules/base-uri/test.filter.js +++ b/webpack-test/configCases/asset-modules/base-uri/test.filter.js @@ -1 +1 @@ -module.exports = () => {return false} \ No newline at end of file +module.exports = () => {return true} \ No newline at end of file diff --git a/webpack-test/configCases/worker/web-worker/test.filter.js b/webpack-test/configCases/worker/web-worker/test.filter.js index 94e079cd7f1..fc4790e0a8a 100644 --- a/webpack-test/configCases/worker/web-worker/test.filter.js +++ b/webpack-test/configCases/worker/web-worker/test.filter.js @@ -5,4 +5,4 @@ // return supportsWorker(); // }; -module.exports = () => {return 'https://github.com/web-infra-dev/rspack/issues/2408'} \ No newline at end of file +module.exports = () => {return true} \ No newline at end of file From c8a731ee5fc03143f5a2a452ed702dcfdfd5f5c0 Mon Sep 17 00:00:00 2001 From: IWANABETHATGUY Date: Tue, 12 Sep 2023 19:23:12 +0800 Subject: [PATCH 12/49] =?UTF-8?q?chore:=20=F0=9F=A4=96=20remove=20unnecess?= =?UTF-8?q?ary=20snapshot=20files=20(#4179)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chore: 🤖 remove unnecessary --- .../fixtures/code-splitting/expected/a_js.js | 6 - .../fixtures/code-splitting/expected/b_js.js | 6 - .../fixtures/code-splitting/expected/main.js | 13 - .../fixtures/dynamic-import/expected/main.js | 38 -- .../simple-with-query/expected/main.js | 35 -- .../fixtures/static-import/expected/main.js | 26 - .../expected/dynamic-1_js.js | 15 - .../expected/dynamic-2_js.js | 15 - .../cycle-dynamic-entry/expected/main.js | 13 - .../cycle-entry/expected/index.js | 20 - .../cycle-entry/expected/index2.js | 20 - .../cycle-entry/expected/index_js.js | 12 - .../intersection/expected/a_js.js | 23 - .../intersection/expected/index.js | 26 - .../intersection/expected/index2.js | 26 - .../self-import/expected/main.js | 12 - .../simple/expected/a_js.js | 11 - .../simple/expected/main.js | 20 - .../array-side-effects/expected/main.js | 43 -- .../assign-with-side-effects/expected/main.js | 36 -- .../tests/tree-shaking/basic/expected/main.js | 51 -- .../tests/tree-shaking/bb/expected/main.js | 44 -- .../expected/main.js | 51 -- .../cjs-tree-shaking-basic/expected/main.js | 42 -- .../class-extend/expected/main.js | 42 -- .../expected/main.js | 29 - .../context-module-elimated/expected/main.js | 16 - .../context-module/expected/main.js | 54 -- .../expected/main.js | 58 -- .../default_export/expected/main.js | 52 -- .../expected/main.js | 31 -- .../expected/main.js | 40 -- .../expected/main.js | 19 - .../expected/main.js | 41 -- .../export-named-decl-as/expected/main.js | 38 -- .../export-star-chain/expected/main.js | 97 ---- .../tree-shaking/export_star/expected/main.js | 58 -- .../export_star2/expected/main.js | 54 -- .../expected/main.js | 53 -- .../expected/main.js | 14 - .../expected/main.js | 76 --- .../import-as-default/expected/main.js | 24 - .../expected/main.js | 37 -- .../expected/main.js | 33 -- .../expected/main.js | 35 -- .../expected/main.js | 58 -- .../tree-shaking/issues_3198/expected/main.js | 23 - .../local-binding-reachable1/expected/main.js | 39 -- .../local-binding-reachable2/expected/main.js | 39 -- .../expected/main.js | 31 -- .../expected/main.js | 31 -- .../expected/main.js | 55 -- .../named_export_alias/expected/main.js | 37 -- .../expected/main.js | 74 --- .../nested-import-3/expected/main.js | 38 -- .../nested-import-4/expected/main.js | 34 -- .../prune-bailout-module/expected/main.js | 33 -- .../react-redux-like/expected/main.js | 57 -- .../expected/main.js | 56 -- .../reexport-all-as/expected/main.js | 42 -- .../reexport_default_as/expected/main.js | 32 -- .../expected/main.js | 43 -- .../expected/main.js | 34 -- .../expected/main.js | 32 -- .../expected/main.js | 32 -- .../expected/main.js | 37 -- .../expected/main.js | 30 -- .../expected/main.js | 63 --- .../rollup-unused-var/expected/main.js | 26 - .../side-effects-analyzed/expected/main.js | 36 -- .../expected/main.js | 25 - .../expected/main.js | 44 -- .../side-effects-prune/expected/main.js | 35 -- .../side-effects-two/expected/main.js | 38 -- .../simple-namespace-access/expected/main.js | 47 -- .../static-class/expected/main.js | 45 -- .../transitive-bailout/expected/main.js | 38 -- .../expected/main.js | 30 -- .../expected/main.js | 34 -- .../tree-shaking-interop/expected/bar_js.js | 11 - .../tree-shaking-interop/expected/main.js | 34 -- .../expected/lib_js.js | 25 - .../tree-shaking-lazy-import/expected/main.js | 25 - .../ts-target-es5/expected/main.js | 508 ------------------ .../var-function-expr/expected/main.js | 43 -- .../expected/main.js | 184 ------- .../expected/main.js | 91 ---- .../expected/chunk_js.js | 9 - .../expected/main.js | 81 --- .../expected/main.js | 132 ----- .../expected/main.js | 39 -- .../expected/main.js | 47 -- .../expected/main.js | 98 ---- .../expected/main.js | 103 ---- .../expected/main.js | 85 --- .../tree-shaking/with-assets/expected/main.js | 28 - 96 files changed, 4396 deletions(-) delete mode 100644 crates/rspack/tests/fixtures/code-splitting/expected/a_js.js delete mode 100644 crates/rspack/tests/fixtures/code-splitting/expected/b_js.js delete mode 100644 crates/rspack/tests/fixtures/code-splitting/expected/main.js delete mode 100644 crates/rspack/tests/fixtures/dynamic-import/expected/main.js delete mode 100644 crates/rspack/tests/fixtures/simple-with-query/expected/main.js delete mode 100644 crates/rspack/tests/fixtures/static-import/expected/main.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-1_js.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-2_js.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/main.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index2.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index_js.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/intersection/expected/a_js.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index2.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/self-import/expected/main.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/simple/expected/a_js.js delete mode 100644 crates/rspack/tests/samples/remove-parent-modules/simple/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/array-side-effects/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/assign-with-side-effects/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/basic/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/bb/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/cjs-export-computed-property/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/cjs-tree-shaking-basic/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/class-extend/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/conflicted_name_by_re_export_all_should_be_hidden/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/context-module-elimated/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/context-module/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/cyclic-reference-export-all/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/default_export/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_1/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_2/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export-all-from-side-effects-free-commonjs/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export-imported-import-all-as/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export-named-decl-as/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export-star-chain/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export_star/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export_star2/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/export_star_conflict_export_no_error/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-imported-unused/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-required/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/import-as-default/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/import-export-all-as-a-empty-module/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/import-star-as-and-export/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/import-var-assign-side-effects/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/inherit_export_map_should_lookup_in_dfs_order/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/issues_3198/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/local-binding-reachable1/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/local-binding-reachable2/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/module-rule-side-effects1/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/module-rule-side-effects2/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/named-export-decl-with-src-eval/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/named_export_alias/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/namespace-access-var-decl-rhs/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/nested-import-3/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/nested-import-4/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/prune-bailout-module/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/react-redux-like/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/reexport-all-as-multi-level-nested/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/reexport-all-as/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/reexport_default_as/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/reexport_entry_elimination/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rename-export-from-import/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports-function-argument/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rollup-unused-called-import/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rollup-unused-default-exports/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rollup-unused-inner-functions-and-classes/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/rollup-unused-var/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/side-effects-analyzed/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/side-effects-export-default-expr/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/side-effects-flagged-only/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/side-effects-prune/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/side-effects-two/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/simple-namespace-access/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/static-class/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/transitive-bailout/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/transitive_side_effects_when_analyze/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/tree-shaking-false-with-side-effect-true/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/bar_js.js delete mode 100644 crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/lib_js.js delete mode 100644 crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/ts-target-es5/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/var-function-expr/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-inner-graph-export-default-named/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-inner-graph-switch/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/chunk_js.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-innergraph-circular2/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-innergraph-no-side-effects/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-innergraph-try-globals/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-reexport-namespace-and-default/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-side-effects-all-used/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/webpack-side-effects-simple-unused/expected/main.js delete mode 100644 crates/rspack/tests/tree-shaking/with-assets/expected/main.js diff --git a/crates/rspack/tests/fixtures/code-splitting/expected/a_js.js b/crates/rspack/tests/fixtures/code-splitting/expected/a_js.js deleted file mode 100644 index a36675cb253..00000000000 --- a/crates/rspack/tests/fixtures/code-splitting/expected/a_js.js +++ /dev/null @@ -1,6 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["a_js"], { -"./a.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('a'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/fixtures/code-splitting/expected/b_js.js b/crates/rspack/tests/fixtures/code-splitting/expected/b_js.js deleted file mode 100644 index 9b2dc743503..00000000000 --- a/crates/rspack/tests/fixtures/code-splitting/expected/b_js.js +++ /dev/null @@ -1,6 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["b_js"], { -"./b.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('b'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/fixtures/code-splitting/expected/main.js b/crates/rspack/tests/fixtures/code-splitting/expected/main.js deleted file mode 100644 index 1e457442034..00000000000 --- a/crates/rspack/tests/fixtures/code-splitting/expected/main.js +++ /dev/null @@ -1,13 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('hello, world'); -__webpack_require__.el(/* ./a */"./a.js").then(__webpack_require__.t.bind(__webpack_require__, /* ./a */"./a.js", 21)); -__webpack_require__.el(/* ./b */"./b.js").then(__webpack_require__.t.bind(__webpack_require__, /* ./b */"./b.js", 21)); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/fixtures/dynamic-import/expected/main.js b/crates/rspack/tests/fixtures/dynamic-import/expected/main.js deleted file mode 100644 index 28921a7709a..00000000000 --- a/crates/rspack/tests/fixtures/dynamic-import/expected/main.js +++ /dev/null @@ -1,38 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./child Lazy recursive ^\\.\\/.*\\.js$": function (module, exports, __webpack_require__) { -var map = {"./a.js": "./child/a.js","./b.js": "./child/b.js",}; - - function webpackAsyncContext(req) { - if(!__webpack_require__.o(map, req)) { - return Promise.resolve().then(function() { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - }); - } - var id = map[req]; - return __webpack_require__.el(id).then(function() { - return __webpack_require__(id); - }); - } - webpackAsyncContext.keys = function() { - return Object.keys(map); - }; - webpackAsyncContext.id = "./child Lazy recursive ^\\.\\/.*\\.js$"; - module.exports = webpackAsyncContext; - }, -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -const request = 'a'; -__webpack_require__.el(/* ./child/a.js */"./child/a.js").then(__webpack_require__.bind(__webpack_require__, /* ./child/a.js */"./child/a.js")).then(({ a })=>console.log("Literal", a)); -__webpack_require__.el(/* ./child/b.js */"./child/b.js").then(__webpack_require__.bind(__webpack_require__, /* ./child/b.js */"./child/b.js")).then(({ b })=>console.log("Template Literal", b)); -__webpack_require__(/* ./child */"./child Lazy recursive ^\\.\\/.*\\.js$")((`./child/${request}.js`).replace('./child/', './')).then(({ a })=>console.log("context_module_tpl", a)); -__webpack_require__(/* ./child */"./child Lazy recursive ^\\.\\/.*\\.js$")(('./child/' + request + '.js').replace('./child/', './')).then(({ a })=>console.log("context_module_bin", a)); -__webpack_require__(/* ./child */"./child Lazy recursive ^\\.\\/.*\\.js$")(("./child/".concat(request, ".js")).replace('./child/', './')).then(({ a })=>console.log("context_module_concat", a)); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/fixtures/simple-with-query/expected/main.js b/crates/rspack/tests/fixtures/simple-with-query/expected/main.js deleted file mode 100644 index 1bb744ca0fb..00000000000 --- a/crates/rspack/tests/fixtures/simple-with-query/expected/main.js +++ /dev/null @@ -1,35 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./b.js?x": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 3; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _b_jsx__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./b.jsx */"./b.jsx"); -/* harmony import */var _b_js_x__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b.js?x */"./b.js?x"); - - -_b_js_x__WEBPACK_IMPORTED_MODULE_1_.a; -_b_jsx__WEBPACK_IMPORTED_MODULE_0_.a; -console.log("hello, world"); -}, -"./b.jsx": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 3; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/fixtures/static-import/expected/main.js b/crates/rspack/tests/fixtures/static-import/expected/main.js deleted file mode 100644 index 150227dcaaf..00000000000 --- a/crates/rspack/tests/fixtures/static-import/expected/main.js +++ /dev/null @@ -1,26 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./b */"./b.js"); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_b__WEBPACK_IMPORTED_MODULE_0_); - -console.log('a'); -}, -"./b.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('b'); -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"./a.js"); - -console.log('hello, world'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-1_js.js b/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-1_js.js deleted file mode 100644 index d8689eb1e54..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-1_js.js +++ /dev/null @@ -1,15 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["dynamic-1_js"], { -"./dynamic-1.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); - -__webpack_require__.el(/* ./dynamic-2 */"./dynamic-2.js").then(__webpack_require__.bind(__webpack_require__, /* ./dynamic-2 */"./dynamic-2.js")); -console.log('dynamic-1'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-2_js.js b/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-2_js.js deleted file mode 100644 index b388b58aecb..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/dynamic-2_js.js +++ /dev/null @@ -1,15 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["dynamic-2_js"], { -"./dynamic-2.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); - -__webpack_require__.el(/* ./dynamic-1 */"./dynamic-1.js").then(__webpack_require__.bind(__webpack_require__, /* ./dynamic-1 */"./dynamic-1.js")); -console.log('dynamic-2'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/main.js b/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/main.js deleted file mode 100644 index 0bcd1cc8c81..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/cycle-dynamic-entry/expected/main.js +++ /dev/null @@ -1,13 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -__webpack_require__.el(/* ./dynamic-1 */"./dynamic-1.js").then(__webpack_require__.bind(__webpack_require__, /* ./dynamic-1 */"./dynamic-1.js")); -__webpack_require__.el(/* ./dynamic-2 */"./dynamic-2.js").then(__webpack_require__.bind(__webpack_require__, /* ./dynamic-2 */"./dynamic-2.js")); -console.log('index'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index.js b/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index.js deleted file mode 100644 index 84f1d0732be..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index.js +++ /dev/null @@ -1,20 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["index"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); -__webpack_require__.el(/* ./index */"./index.js").then(__webpack_require__.bind(__webpack_require__, /* ./index */"./index.js")); - -console.log('index1'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index2.js b/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index2.js deleted file mode 100644 index 8b8d912c2bc..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index2.js +++ /dev/null @@ -1,20 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["index2"], { -"./index2.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); -__webpack_require__.el(/* ./index */"./index.js").then(__webpack_require__.bind(__webpack_require__, /* ./index */"./index.js")); - -console.log('index2'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index2.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index_js.js b/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index_js.js deleted file mode 100644 index 530dab7987c..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/cycle-entry/expected/index_js.js +++ /dev/null @@ -1,12 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["index_js"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); -__webpack_require__.el(/* ./index */"./index.js").then(__webpack_require__.bind(__webpack_require__, /* ./index */"./index.js")); - -console.log('index1'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/a_js.js b/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/a_js.js deleted file mode 100644 index c123399cfce..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/a_js.js +++ /dev/null @@ -1,23 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["a_js"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); -/* harmony import */var _i_1__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./i-1 */"./i-1.js"); -/* harmony import */var _i_1__WEBPACK_IMPORTED_MODULE_1__default = /*#__PURE__*/__webpack_require__.n(_i_1__WEBPACK_IMPORTED_MODULE_1_); -/* harmony import */var _i_2__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./i-2 */"./i-2.js"); -/* harmony import */var _i_2__WEBPACK_IMPORTED_MODULE_2__default = /*#__PURE__*/__webpack_require__.n(_i_2__WEBPACK_IMPORTED_MODULE_2_); - - - -console.log('a'); -}, -"./i-1.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('i-1'); -}, -"./i-2.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('i-2'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index.js b/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index.js deleted file mode 100644 index d9c78962157..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index.js +++ /dev/null @@ -1,26 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["index"], { -"./i-1.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('i-1'); -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); -/* harmony import */var _i_1__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./i-1 */"./i-1.js"); -/* harmony import */var _i_1__WEBPACK_IMPORTED_MODULE_1__default = /*#__PURE__*/__webpack_require__.n(_i_1__WEBPACK_IMPORTED_MODULE_1_); - - -__webpack_require__.el(/* ./a */"./a.js").then(__webpack_require__.bind(__webpack_require__, /* ./a */"./a.js")); -console.log('index'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index2.js b/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index2.js deleted file mode 100644 index 95640273581..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/intersection/expected/index2.js +++ /dev/null @@ -1,26 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["index2"], { -"./i-2.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('i-2'); -}, -"./index2.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); -/* harmony import */var _i_2__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./i-2 */"./i-2.js"); -/* harmony import */var _i_2__WEBPACK_IMPORTED_MODULE_1__default = /*#__PURE__*/__webpack_require__.n(_i_2__WEBPACK_IMPORTED_MODULE_1_); - - -__webpack_require__.el(/* ./a */"./a.js").then(__webpack_require__.bind(__webpack_require__, /* ./a */"./a.js")); -console.log('index'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index2.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/self-import/expected/main.js b/crates/rspack/tests/samples/remove-parent-modules/self-import/expected/main.js deleted file mode 100644 index 0112289f07d..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/self-import/expected/main.js +++ /dev/null @@ -1,12 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -__webpack_require__.el(/* ./index */"./index.js").then(__webpack_require__.t.bind(__webpack_require__, /* ./index */"./index.js", 21)); -console.log('index'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/simple/expected/a_js.js b/crates/rspack/tests/samples/remove-parent-modules/simple/expected/a_js.js deleted file mode 100644 index 9f96e228983..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/simple/expected/a_js.js +++ /dev/null @@ -1,11 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["a_js"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); - -console.log('a'); -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/samples/remove-parent-modules/simple/expected/main.js b/crates/rspack/tests/samples/remove-parent-modules/simple/expected/main.js deleted file mode 100644 index e5f21528a9f..00000000000 --- a/crates/rspack/tests/samples/remove-parent-modules/simple/expected/main.js +++ /dev/null @@ -1,20 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./shared */"./shared.js"); -/* harmony import */var _shared__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_shared__WEBPACK_IMPORTED_MODULE_0_); - -__webpack_require__.el(/* ./a */"./a.js").then(__webpack_require__.bind(__webpack_require__, /* ./a */"./a.js")); -console.log('index'); -}, -"./shared.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log('shared'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/array-side-effects/expected/main.js b/crates/rspack/tests/tree-shaking/array-side-effects/expected/main.js deleted file mode 100644 index 9c2a921d8ff..00000000000 --- a/crates/rspack/tests/tree-shaking/array-side-effects/expected/main.js +++ /dev/null @@ -1,43 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'app': function() { return app; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - function app() {} -app.prototype.result = _lib__WEBPACK_IMPORTED_MODULE_0_.result; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _src_a__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./src/a */"./src/a.js"); - - -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'result': function() { return result; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -}, -"./src/a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_.app; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/assign-with-side-effects/expected/main.js b/crates/rspack/tests/tree-shaking/assign-with-side-effects/expected/main.js deleted file mode 100644 index 5f8f27c33e3..00000000000 --- a/crates/rspack/tests/tree-shaking/assign-with-side-effects/expected/main.js +++ /dev/null @@ -1,36 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'app': function() { return app; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - function app() {} -app.prototype.result = _lib__WEBPACK_IMPORTED_MODULE_0_.result; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.app)(); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'result': function() { return result; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/basic/expected/main.js b/crates/rspack/tests/tree-shaking/basic/expected/main.js deleted file mode 100644 index c30b097d79f..00000000000 --- a/crates/rspack/tests/tree-shaking/basic/expected/main.js +++ /dev/null @@ -1,51 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'answer': function() { return answer; } -}); - const answer = 103330; -}, -"./app.js": function (module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -setTimeout(()=>{ - console.log(_lib__WEBPACK_IMPORTED_MODULE_0_.myanswer); -}, 1000); - function render() { - function test() { - const container = document.getElementById("root"); - container.innerHTML = `adddd333:${/* "./lib" unused */null}:${_lib__WEBPACK_IMPORTED_MODULE_0_.myanswer}`; - } -} -if (module.hot?.accept) module.hot.accept((module1)=>{ - console.log("xxx:", module1); -}); -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'myanswer': function() { return myanswer; } -}); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); - - const secret = "888"; - const myanswer = _answer__WEBPACK_IMPORTED_MODULE_0_.answer, result = 20000; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/bb/expected/main.js b/crates/rspack/tests/tree-shaking/bb/expected/main.js deleted file mode 100644 index 3bb5bbed62a..00000000000 --- a/crates/rspack/tests/tree-shaking/bb/expected/main.js +++ /dev/null @@ -1,44 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _b_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./b.js */"./b.js"); -/* harmony import */var _c_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./c.js */"./c.js"); -__webpack_require__.es(_c_js__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - - - const a = 3; -_b_js__WEBPACK_IMPORTED_MODULE_0_.d; - -}, -"./b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'd': function() { return d; } -}); - const d = 3; - const c = 100; -}, -"./c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'ccc': function() { return ccc; } -}); - const ccc = 30; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); - -_a_js__WEBPACK_IMPORTED_MODULE_0_.ccc; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/cjs-export-computed-property/expected/main.js b/crates/rspack/tests/tree-shaking/cjs-export-computed-property/expected/main.js deleted file mode 100644 index e7c20a1a9a2..00000000000 --- a/crates/rspack/tests/tree-shaking/cjs-export-computed-property/expected/main.js +++ /dev/null @@ -1,51 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./zh_locale.js": function (__unused_webpack_module, exports, __webpack_require__) { -"use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; -/* eslint-disable no-template-curly-in-string */ var _default = {}; -exports["default"] = _default; -}, -"./antd/index.ts": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'locales': function() { return locales; } -}); -/* harmony import */var _locale_zh__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../locale_zh */"./locale_zh.ts"); - -const locales = { - zh_CN: _locale_zh__WEBPACK_IMPORTED_MODULE_0_["default"] -}; - -}, -"./index.ts": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'test': function() { return test; } -}); -/* harmony import */var _antd_index__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./antd/index */"./antd/index.ts"); - -_antd_index__WEBPACK_IMPORTED_MODULE_0_.locales.zh_CN; - function test() {} -}, -"./locale_zh.ts": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _zh_locale__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./zh_locale */"./zh_locale.js"); - -var __WEBPACK_DEFAULT_EXPORT__ = _zh_locale__WEBPACK_IMPORTED_MODULE_0_["default"]; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.ts")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/cjs-tree-shaking-basic/expected/main.js b/crates/rspack/tests/tree-shaking/cjs-tree-shaking-basic/expected/main.js deleted file mode 100644 index d7d11798498..00000000000 --- a/crates/rspack/tests/tree-shaking/cjs-tree-shaking-basic/expected/main.js +++ /dev/null @@ -1,42 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'answer': function() { return answer; } -}); - - const answer = 42; -}, -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'myanswer': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_.myanswer; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./app */"./app.js"); - -__webpack_require__(/* ./answer */"./answer.js"); -(0, _app__WEBPACK_IMPORTED_MODULE_1_.myanswer)(); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'myanswer': function() { return myanswer; } -}); - const myanswer = 'anyser'; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/class-extend/expected/main.js b/crates/rspack/tests/tree-shaking/class-extend/expected/main.js deleted file mode 100644 index 2417366efe4..00000000000 --- a/crates/rspack/tests/tree-shaking/class-extend/expected/main.js +++ /dev/null @@ -1,42 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'v': function() { return v; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - class Lib extends /* "./lib" unused */null { -} -function foo() { - return { - OriginLib: /* "./lib" unused */null - }; -} - const v = _lib__WEBPACK_IMPORTED_MODULE_0_.value; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_.v; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'value': function() { return value; } -}); - class Lib { -} - const value = 1; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/conflicted_name_by_re_export_all_should_be_hidden/expected/main.js b/crates/rspack/tests/tree-shaking/conflicted_name_by_re_export_all_should_be_hidden/expected/main.js deleted file mode 100644 index 3b69bc78141..00000000000 --- a/crates/rspack/tests/tree-shaking/conflicted_name_by_re_export_all_should_be_hidden/expected/main.js +++ /dev/null @@ -1,29 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const a = 'bar'; -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const a = 'foo'; - const b = 'foo'; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -__webpack_require__.es(_foo__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/context-module-elimated/expected/main.js b/crates/rspack/tests/tree-shaking/context-module-elimated/expected/main.js deleted file mode 100644 index 899475de62c..00000000000 --- a/crates/rspack/tests/tree-shaking/context-module-elimated/expected/main.js +++ /dev/null @@ -1,16 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - -function test() { - /* "./lib.js" unused */null; -} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/context-module/expected/main.js b/crates/rspack/tests/tree-shaking/context-module/expected/main.js deleted file mode 100644 index 2420a88eef3..00000000000 --- a/crates/rspack/tests/tree-shaking/context-module/expected/main.js +++ /dev/null @@ -1,54 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./child/child/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'value': function() { return value; } -}); - const value = "dynamic"; -}, -"./child/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'value': function() { return value; } -}); - const value = "dynamic"; -}, -"./child Sync recursive ^\\.\\/.*\\.js$": function (module, exports, __webpack_require__) { -var map = {"./child/index.js": "./child/child/index.js","./index.js": "./child/index.js",}; -function webpackContext(req) { -var id = webpackContextResolve(req); - -return __webpack_require__(id); - -} -function webpackContextResolve(req) { - - if(!__webpack_require__.o(map, req)) { - var e = new Error("Cannot find module '" + req + "'"); - e.code = 'MODULE_NOT_FOUND'; - throw e; - } - return map[req]; - -} -webpackContext.id = '"./child Sync recursive ^\\.\\/.*\\.js$"'; - - webpackContext.keys = function webpackContextKeys() { - return Object.keys(map); - }; - webpackContext.resolve = webpackContextResolve; - module.exports = webpackContext; - }, -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -let a = "index"; -__webpack_require__(/* ./child */"./child Sync recursive ^\\.\\/.*\\.js$")((`./child/${a}.js`).replace('./child/', './')); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/cyclic-reference-export-all/expected/main.js b/crates/rspack/tests/tree-shaking/cyclic-reference-export-all/expected/main.js deleted file mode 100644 index 31abe01bf38..00000000000 --- a/crates/rspack/tests/tree-shaking/cyclic-reference-export-all/expected/main.js +++ /dev/null @@ -1,58 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./src/App.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _containers__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./containers */"./src/containers/index.js"); - -const { PlatformProvider } = _containers__WEBPACK_IMPORTED_MODULE_0_.containers; -const Index = ()=>{ - console.log("PlatformProvider", PlatformProvider); - return 'something'; -}; -var __WEBPACK_DEFAULT_EXPORT__ = Index; -}, -"./src/containers/containers.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _platform_container__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./platform-container */"./src/containers/platform-container/index.js"); -__webpack_require__.es(_platform_container__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - - -}, -"./src/containers/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'containers': function() { return _containers__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _containers__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./containers */"./src/containers/containers.js"); - - -}, -"./src/containers/platform-container/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'usePlatform': function() { return usePlatform; }, - 'PlatformProvider': function() { return PlatformProvider; } -}); - const usePlatform = 3; - const PlatformProvider = 1000; -}, -"./src/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _App__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./App */"./src/App.js"); - -(0, _App__WEBPACK_IMPORTED_MODULE_0_["default"])(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./src/index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/default_export/expected/main.js b/crates/rspack/tests/tree-shaking/default_export/expected/main.js deleted file mode 100644 index 76bffe6eb92..00000000000 --- a/crates/rspack/tests/tree-shaking/default_export/expected/main.js +++ /dev/null @@ -1,52 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'answer': function() { return answer; } -}); - const answer = 103330; // export default answer; -}, -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'render': function() { return render; }, - 'default': function() { return result; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - function render() { - function test() { - const container = document.getElementById("root"); - container.innerHTML = `adddd333:${_lib__WEBPACK_IMPORTED_MODULE_0_.secret}:${_lib__WEBPACK_IMPORTED_MODULE_0_.myanswer}`; - } -} -function result() {} -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.render)(_app__WEBPACK_IMPORTED_MODULE_0_["default"]); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'secret': function() { return secret; }, - 'myanswer': function() { return myanswer; } -}); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); - - const secret = "888"; - const myanswer = _answer__WEBPACK_IMPORTED_MODULE_0_.answer, result = 20000; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_1/expected/main.js b/crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_1/expected/main.js deleted file mode 100644 index e51ef185893..00000000000 --- a/crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_1/expected/main.js +++ /dev/null @@ -1,31 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const a = 'bar'; -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - const a = 'foo'; - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -console.log(_foo__WEBPACK_IMPORTED_MODULE_0_.a); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_2/expected/main.js b/crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_2/expected/main.js deleted file mode 100644 index 30905d6282e..00000000000 --- a/crates/rspack/tests/tree-shaking/explicit_named_export_higher_priority_2/expected/main.js +++ /dev/null @@ -1,40 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const a = 'bar'; -}, -"./baz.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 'baz'; -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return _baz__WEBPACK_IMPORTED_MODULE_0_.a; } -}); -/* harmony import */var _baz__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./baz */"./baz.js"); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -console.log(_foo__WEBPACK_IMPORTED_MODULE_0_.a); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export-all-from-side-effects-free-commonjs/expected/main.js b/crates/rspack/tests/tree-shaking/export-all-from-side-effects-free-commonjs/expected/main.js deleted file mode 100644 index 0bb858e3111..00000000000 --- a/crates/rspack/tests/tree-shaking/export-all-from-side-effects-free-commonjs/expected/main.js +++ /dev/null @@ -1,19 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -var _lib__WEBPACK_IMPORTED_MODULE_0__namespace_cache; -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -/*#__PURE__*/ (_lib__WEBPACK_IMPORTED_MODULE_0__namespace_cache || (_lib__WEBPACK_IMPORTED_MODULE_0__namespace_cache = __webpack_require__.t(_lib__WEBPACK_IMPORTED_MODULE_0_, 2))); -}, -"./lib.js": function (__unused_webpack_module, exports, __webpack_require__) { -exports['a'] = 100000; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export-imported-import-all-as/expected/main.js b/crates/rspack/tests/tree-shaking/export-imported-import-all-as/expected/main.js deleted file mode 100644 index 1c20d5ccfde..00000000000 --- a/crates/rspack/tests/tree-shaking/export-imported-import-all-as/expected/main.js +++ /dev/null @@ -1,41 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); -__webpack_require__.es(_lib__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); - -_answer__WEBPACK_IMPORTED_MODULE_0_.filter; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'filter': function() { return _test_js__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _test_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./test.js */"./test.js"); - const a = 3; - - -}, -"./test.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'result': function() { return result; } -}); - const result = ""; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export-named-decl-as/expected/main.js b/crates/rspack/tests/tree-shaking/export-named-decl-as/expected/main.js deleted file mode 100644 index 3a09eee5f44..00000000000 --- a/crates/rspack/tests/tree-shaking/export-named-decl-as/expected/main.js +++ /dev/null @@ -1,38 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./src/answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'formatNumber': function() { return _plugin_formatNumber__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _plugin_formatNumber__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./plugin/formatNumber */"./src/plugin/formatNumber.js"); - - -}, -"./src/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./src/answer.js"); - -console.log(_answer__WEBPACK_IMPORTED_MODULE_0_); -}, -"./src/plugin/formatNumber.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return formatNumber_default; } -}); -function formatNumber(config) {} -const plugin = (cls)=>{ - cls.prototype.formatNumber = formatNumber; -}; -var formatNumber_default = plugin; - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./src/index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export-star-chain/expected/main.js b/crates/rspack/tests/tree-shaking/export-star-chain/expected/main.js deleted file mode 100644 index 9c2c40c78e8..00000000000 --- a/crates/rspack/tests/tree-shaking/export-star-chain/expected/main.js +++ /dev/null @@ -1,97 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./Layout.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _something__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./something */"./something/index.js"); -__webpack_require__.es(_something__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - - -}, -"./colors/a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'red': function() { return red; } -}); - const red = 'red'; -}, -"./colors/b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'blue': function() { return blue; } -}); - const blue = 'blue'; -}, -"./colors/c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _result__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./result */"./colors/result.js"); -__webpack_require__.es(_result__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./colors/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"./colors/a.js"); -__webpack_require__.es(_a__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b */"./colors/b.js"); -__webpack_require__.es(_b__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); -/* harmony import */var _c__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./c */"./colors/c.js"); -__webpack_require__.es(_c__WEBPACK_IMPORTED_MODULE_2_, __webpack_exports__); - - - -}, -"./colors/result.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'result': function() { return result; } -}); - const result = 'ssss'; -}, -"./export.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _Layout__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./Layout */"./Layout.js"); -__webpack_require__.es(_Layout__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _export__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./export */"./export.js"); - -_export__WEBPACK_IMPORTED_MODULE_0_.Colors; -_export__WEBPACK_IMPORTED_MODULE_0_.Something; -}, -"./something/Something.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Something': function() { return Something; } -}); - class Something { -} -}, -"./something/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Colors': function() { return _colors_index__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _colors_index__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../colors/index */"./colors/index.js"); -/* harmony import */var _Something__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./Something */"./something/Something.js"); -__webpack_require__.es(_Something__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export_star/expected/main.js b/crates/rspack/tests/tree-shaking/export_star/expected/main.js deleted file mode 100644 index 0a956b1c104..00000000000 --- a/crates/rspack/tests/tree-shaking/export_star/expected/main.js +++ /dev/null @@ -1,58 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'bar': function() { return _foo__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -/* harmony import */var _result__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./result */"./result.js"); -__webpack_require__.es(_result__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - function b() {} - - -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _result__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./result */"./result.js"); -__webpack_require__.es(_result__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - const a = 3; - const foo = 3; - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -_foo__WEBPACK_IMPORTED_MODULE_0_.bar.a; -(0, _foo__WEBPACK_IMPORTED_MODULE_0_.c)(); -}, -"./result.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'c': function() { return c; } -}); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -__webpack_require__.es(_foo__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - const c = 103330; - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export_star2/expected/main.js b/crates/rspack/tests/tree-shaking/export_star2/expected/main.js deleted file mode 100644 index 23ad4db46ca..00000000000 --- a/crates/rspack/tests/tree-shaking/export_star2/expected/main.js +++ /dev/null @@ -1,54 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -__webpack_require__.es(_foo__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _result__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./result */"./result.js"); -__webpack_require__.es(_result__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - function b() {} - - -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _result__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./result */"./result.js"); -__webpack_require__.es(_result__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - const a = 3; - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -__webpack_require__.es(_foo__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); -/* harmony import */var _result__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./result */"./result.js"); -__webpack_require__.es(_result__WEBPACK_IMPORTED_MODULE_2_, __webpack_exports__); - - - -}, -"./result.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -__webpack_require__.es(_foo__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - const c = 103330; - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/export_star_conflict_export_no_error/expected/main.js b/crates/rspack/tests/tree-shaking/export_star_conflict_export_no_error/expected/main.js deleted file mode 100644 index 7ef071b08df..00000000000 --- a/crates/rspack/tests/tree-shaking/export_star_conflict_export_no_error/expected/main.js +++ /dev/null @@ -1,53 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'b': function() { return b; } -}); -/* harmony import */var _foo_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo.js */"./foo.js"); -__webpack_require__.es(_foo_js__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _result_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./result.js */"./result.js"); -__webpack_require__.es(_result_js__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - function b() {} - - -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _bar_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./bar.js */"./bar.js"); -__webpack_require__.es(_bar_js__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _result_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./result.js */"./result.js"); -__webpack_require__.es(_result_js__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - const a = 3; - const b = 3; - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _bar_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./bar.js */"./bar.js"); - -(0, _bar_js__WEBPACK_IMPORTED_MODULE_0_.b)(); -}, -"./result.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo.js */"./foo.js"); -__webpack_require__.es(_foo_js__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _bar_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar.js */"./bar.js"); -__webpack_require__.es(_bar_js__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - const c = 103330; - const b = 103330; - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-imported-unused/expected/main.js b/crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-imported-unused/expected/main.js deleted file mode 100644 index ee575edea66..00000000000 --- a/crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-imported-unused/expected/main.js +++ /dev/null @@ -1,14 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - -console.log('something'); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-required/expected/main.js b/crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-required/expected/main.js deleted file mode 100644 index 1102ae68cbc..00000000000 --- a/crates/rspack/tests/tree-shaking/handle-side-effects-commonjs-required/expected/main.js +++ /dev/null @@ -1,76 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -__webpack_require__(/* ./source */"./source/index.js"); -console.log('something'); -}, -"./source/index.js": function (module, exports, __webpack_require__) { -var _class_call_check = __webpack_require__(/* @swc/helpers/_/_class_call_check */"../../../../../node_modules/@swc/helpers/esm/_class_call_check.js"); -var _create_class = __webpack_require__(/* @swc/helpers/_/_create_class */"../../../../../node_modules/@swc/helpers/esm/_create_class.js"); -var test = function test() { - var res = new Response(); - return res; -}; -var Response = function() { - "use strict"; - function Response(mode) { - _class_call_check._(this, Response); - // eslint-disable-next-line no-undefined - if (mode.data === undefined) mode.data = {}; - this.data = mode.data; - this.isMatchIgnored = false; - } - _create_class._(Response, [ - { - key: "ignoreMatch", - value: function ignoreMatch() { - this.isMatchIgnored = true; - } - } - ]); - return Response; -}(); -var result = test(); -module.exports = result; -}, -"../../../../../node_modules/@swc/helpers/esm/_class_call_check.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - '_class_call_check': function() { return _class_call_check; }, - '_': function() { return _class_call_check; } -}); - function _class_call_check(instance, Constructor) { - if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); -} - -}, -"../../../../../node_modules/@swc/helpers/esm/_create_class.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - '_create_class': function() { return _create_class; }, - '_': function() { return _create_class; } -}); -function _defineProperties(target, props) { - for(var i = 0; i < props.length; i++){ - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} - function _create_class(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/import-as-default/expected/main.js b/crates/rspack/tests/tree-shaking/import-as-default/expected/main.js deleted file mode 100644 index 6a53cc37b5f..00000000000 --- a/crates/rspack/tests/tree-shaking/import-as-default/expected/main.js +++ /dev/null @@ -1,24 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -var a = 1; -var __WEBPACK_DEFAULT_EXPORT__ = a; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_["default"]; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/import-export-all-as-a-empty-module/expected/main.js b/crates/rspack/tests/tree-shaking/import-export-all-as-a-empty-module/expected/main.js deleted file mode 100644 index 2e8f9b1c1bb..00000000000 --- a/crates/rspack/tests/tree-shaking/import-export-all-as-a-empty-module/expected/main.js +++ /dev/null @@ -1,37 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'aaa': function() { return _app__WEBPACK_IMPORTED_MODULE_1_; }, - 'routes': function() { return routes; } -}); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_answer__WEBPACK_IMPORTED_MODULE_0_); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./app */"./app.js"); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_1__default = /*#__PURE__*/__webpack_require__.n(_app__WEBPACK_IMPORTED_MODULE_1_); - - - const routes = { - answer: _answer__WEBPACK_IMPORTED_MODULE_0_.something -}; -}, -"./answer.js": function (__unused_webpack_module, exports, __webpack_require__) { -}, -"./app.js": function (__unused_webpack_module, exports, __webpack_require__) { -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); - -_a_js__WEBPACK_IMPORTED_MODULE_0_.routes; -_a_js__WEBPACK_IMPORTED_MODULE_0_.aaa.result; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/import-star-as-and-export/expected/main.js b/crates/rspack/tests/tree-shaking/import-star-as-and-export/expected/main.js deleted file mode 100644 index b8a860a638c..00000000000 --- a/crates/rspack/tests/tree-shaking/import-star-as-and-export/expected/main.js +++ /dev/null @@ -1,33 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'app': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_.app; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 20000; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/import-var-assign-side-effects/expected/main.js b/crates/rspack/tests/tree-shaking/import-var-assign-side-effects/expected/main.js deleted file mode 100644 index cf30bb3f166..00000000000 --- a/crates/rspack/tests/tree-shaking/import-var-assign-side-effects/expected/main.js +++ /dev/null @@ -1,35 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./Something.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return Something; } -}); -class Something { -} -}, -"./export.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Sider': function() { return _Something__WEBPACK_IMPORTED_MODULE_1_["default"]; } -}); -/* harmony import */var _Something__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./Something */"./Something.js"); - - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _export__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./export */"./export.js"); - -(0, _export__WEBPACK_IMPORTED_MODULE_0_.Sider)(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/inherit_export_map_should_lookup_in_dfs_order/expected/main.js b/crates/rspack/tests/tree-shaking/inherit_export_map_should_lookup_in_dfs_order/expected/main.js deleted file mode 100644 index a4bc8805daf..00000000000 --- a/crates/rspack/tests/tree-shaking/inherit_export_map_should_lookup_in_dfs_order/expected/main.js +++ /dev/null @@ -1,58 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'c': function() { return c; } -}); - const c = 'a'; -}, -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const a = 'bar'; - const c = 'bar'; -}, -"./c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -__webpack_require__.es(_foo__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./bar */"./bar.js"); -__webpack_require__.es(_bar__WEBPACK_IMPORTED_MODULE_1_, __webpack_exports__); - - - const a = 3; -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'b': function() { return b; } -}); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); -__webpack_require__.es(_a_js__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - - const a = 'foo'; - const b = 'foo'; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _c_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./c.js */"./c.js"); -// require("./c.js"); - -_c_js__WEBPACK_IMPORTED_MODULE_0_.a; -_c_js__WEBPACK_IMPORTED_MODULE_0_.b; -_c_js__WEBPACK_IMPORTED_MODULE_0_.c; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/issues_3198/expected/main.js b/crates/rspack/tests/tree-shaking/issues_3198/expected/main.js deleted file mode 100644 index b0480b0bd82..00000000000 --- a/crates/rspack/tests/tree-shaking/issues_3198/expected/main.js +++ /dev/null @@ -1,23 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _test__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./test */"./test.js"); - -_test__WEBPACK_IMPORTED_MODULE_0_.obj.test = 1; -}, -"./test.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'obj': function() { return obj; } -}); - const obj = {}; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/local-binding-reachable1/expected/main.js b/crates/rspack/tests/tree-shaking/local-binding-reachable1/expected/main.js deleted file mode 100644 index 786404aff93..00000000000 --- a/crates/rspack/tests/tree-shaking/local-binding-reachable1/expected/main.js +++ /dev/null @@ -1,39 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./Layout.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'defaults': function() { return defaults; } -}); - const defaults = { - test: 1000 -}; -}, -"./export.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Something': function() { return Something; } -}); -/* harmony import */var _Layout__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./Layout */"./Layout.js"); - - function callit() { - _Layout__WEBPACK_IMPORTED_MODULE_0_.defaults.test; -} - var Sider = callit(); - var Something = 20000; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _export__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./export */"./export.js"); - -(0, _export__WEBPACK_IMPORTED_MODULE_0_.Something)(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/local-binding-reachable2/expected/main.js b/crates/rspack/tests/tree-shaking/local-binding-reachable2/expected/main.js deleted file mode 100644 index 3609e070745..00000000000 --- a/crates/rspack/tests/tree-shaking/local-binding-reachable2/expected/main.js +++ /dev/null @@ -1,39 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./Layout.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'defaults': function() { return defaults; } -}); - const defaults = { - test: 1000 -}; -}, -"./export.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Something': function() { return Something; } -}); -/* harmony import */var _Layout__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./Layout */"./Layout.js"); - -class Test { - test = _Layout__WEBPACK_IMPORTED_MODULE_0_.defaults.test + 20000; -} - var Sider = new Test(); - var Something = 333; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _export__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./export */"./export.js"); - -(0, _export__WEBPACK_IMPORTED_MODULE_0_.Something)(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/module-rule-side-effects1/expected/main.js b/crates/rspack/tests/tree-shaking/module-rule-side-effects1/expected/main.js deleted file mode 100644 index c8af6ca1701..00000000000 --- a/crates/rspack/tests/tree-shaking/module-rule-side-effects1/expected/main.js +++ /dev/null @@ -1,31 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 3; -}, -"./c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const c = 300; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); -/* harmony import */var _c_js__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./c.js */"./c.js"); - - - -_a_js__WEBPACK_IMPORTED_MODULE_0_.a; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/module-rule-side-effects2/expected/main.js b/crates/rspack/tests/tree-shaking/module-rule-side-effects2/expected/main.js deleted file mode 100644 index cace7db086d..00000000000 --- a/crates/rspack/tests/tree-shaking/module-rule-side-effects2/expected/main.js +++ /dev/null @@ -1,31 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 3; -}, -"./b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); - const b = 30; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); -/* harmony import */var _b_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b.js */"./b.js"); - - - -_a_js__WEBPACK_IMPORTED_MODULE_0_.a; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/named-export-decl-with-src-eval/expected/main.js b/crates/rspack/tests/tree-shaking/named-export-decl-with-src-eval/expected/main.js deleted file mode 100644 index 94328ad69b3..00000000000 --- a/crates/rspack/tests/tree-shaking/named-export-decl-with-src-eval/expected/main.js +++ /dev/null @@ -1,55 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./Layout.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return Layout; } -}); -function Layout() {} -}, -"./Something.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'something': function() { return something; } -}); - function something() {} -}, -"./c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'cccc': function() { return cccc; } -}); - function cccc() {} -}, -"./export.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'cccc': function() { return _c__WEBPACK_IMPORTED_MODULE_2_.cccc; } -}); -/* harmony import */var _Layout__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./Layout */"./Layout.js"); -/* harmony import */var _Something__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./Something */"./Something.js"); -/* harmony import */var _c__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./c */"./c.js"); - - -var L = _Layout__WEBPACK_IMPORTED_MODULE_0_["default"]; -L.something = _Something__WEBPACK_IMPORTED_MODULE_1_.something; - - var LL = L; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _export__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./export */"./export.js"); - -(0, _export__WEBPACK_IMPORTED_MODULE_0_.cccc)(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/named_export_alias/expected/main.js b/crates/rspack/tests/tree-shaking/named_export_alias/expected/main.js deleted file mode 100644 index 4b39da4c7a0..00000000000 --- a/crates/rspack/tests/tree-shaking/named_export_alias/expected/main.js +++ /dev/null @@ -1,37 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./Something.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'something': function() { return something; } -}); - function something() {} -}, -"./export.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return a; } -}); -/* harmony import */var _Something__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./Something */"./Something.js"); - - -var a = function test() { - _Something__WEBPACK_IMPORTED_MODULE_1_.something; -}; - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _export__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./export */"./export.js"); - -_export__WEBPACK_IMPORTED_MODULE_0_["default"]; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/namespace-access-var-decl-rhs/expected/main.js b/crates/rspack/tests/tree-shaking/namespace-access-var-decl-rhs/expected/main.js deleted file mode 100644 index 2a5ec0321c1..00000000000 --- a/crates/rspack/tests/tree-shaking/namespace-access-var-decl-rhs/expected/main.js +++ /dev/null @@ -1,74 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = { - a: '' -}; -}, -"./b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'b': function() { return b; } -}); - const b = { - b: "" -}; -}, -"./enum-old.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return _a__WEBPACK_IMPORTED_MODULE_0_.a; }, - 'b': function() { return _b__WEBPACK_IMPORTED_MODULE_1_.b; } -}); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"./a.js"); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b */"./b.js"); - - -}, -"./enum.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _enum_old__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./enum-old */"./enum-old.js"); -__webpack_require__.es(_enum_old__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -console.log(_lib__WEBPACK_IMPORTED_MODULE_0_.getDocPermissionTextSendMe); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'getDocPermissionTextSendMe': function() { return getDocPermissionTextSendMe; } -}); -/* harmony import */var _enum_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./enum.js */"./enum.js"); - -function Record() {} - const code2CreateChatDocPermission = { - 1: _enum_js__WEBPACK_IMPORTED_MODULE_0_.a.a -}; - function getDocPermissionTextSendMe() {} - class Doc extends Record({}) { - isSheet() { - return this.type === _enum_js__WEBPACK_IMPORTED_MODULE_0_.b.b; - } -} -Doc.fromJS = (data)=>new Doc(data); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/nested-import-3/expected/main.js b/crates/rspack/tests/tree-shaking/nested-import-3/expected/main.js deleted file mode 100644 index 5b7f0285404..00000000000 --- a/crates/rspack/tests/tree-shaking/nested-import-3/expected/main.js +++ /dev/null @@ -1,38 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 103330; - const b = 103330; -}, -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); -__webpack_require__.es(_answer__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -_lib__WEBPACK_IMPORTED_MODULE_0_.a; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); -__webpack_require__.es(_app__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/nested-import-4/expected/main.js b/crates/rspack/tests/tree-shaking/nested-import-4/expected/main.js deleted file mode 100644 index e2fb9567007..00000000000 --- a/crates/rspack/tests/tree-shaking/nested-import-4/expected/main.js +++ /dev/null @@ -1,34 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./answer.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 103330; - const b = 103330; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -_lib__WEBPACK_IMPORTED_MODULE_0_.Lib.a; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Lib': function() { return _answer__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/prune-bailout-module/expected/main.js b/crates/rspack/tests/tree-shaking/prune-bailout-module/expected/main.js deleted file mode 100644 index ea63856c835..00000000000 --- a/crates/rspack/tests/tree-shaking/prune-bailout-module/expected/main.js +++ /dev/null @@ -1,33 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -var __WEBPACK_DEFAULT_EXPORT__ = 300; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - -_lib__WEBPACK_IMPORTED_MODULE_0_.a; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return _a_js__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); - - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/react-redux-like/expected/main.js b/crates/rspack/tests/tree-shaking/react-redux-like/expected/main.js deleted file mode 100644 index a4dcf2265e4..00000000000 --- a/crates/rspack/tests/tree-shaking/react-redux-like/expected/main.js +++ /dev/null @@ -1,57 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Provider': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_["default"]; }, - 'useSelector': function() { return _selector_js__WEBPACK_IMPORTED_MODULE_1_["default"]; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); -/* harmony import */var _selector_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./selector.js */"./selector.js"); - - - -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); -__webpack_require__.es(_app__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -function batch() {} - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -_foo__WEBPACK_IMPORTED_MODULE_0_.Provider; -_foo__WEBPACK_IMPORTED_MODULE_0_.useSelector; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -function Provider() {} -var __WEBPACK_DEFAULT_EXPORT__ = Provider; -}, -"./selector.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return useSelector; } -}); -function useSelector() { - return ""; -} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/reexport-all-as-multi-level-nested/expected/main.js b/crates/rspack/tests/tree-shaking/reexport-all-as-multi-level-nested/expected/main.js deleted file mode 100644 index 2fb691dca03..00000000000 --- a/crates/rspack/tests/tree-shaking/reexport-all-as-multi-level-nested/expected/main.js +++ /dev/null @@ -1,56 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./package/autogen/a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; }, - 'aa': function() { return _aa__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _aa__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./aa */"./package/autogen/aa.js"); - - function a() {} - function dddd() {} - -}, -"./package/autogen/aa.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'aa': function() { return aa; } -}); - const aa = 3; - const cc = 3; -}, -"./package/autogen/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return _a__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"./package/autogen/a.js"); - - - -}, -"./package/src/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _autogen_index__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../autogen/index */"./package/autogen/index.js"); -__webpack_require__.es(_autogen_index__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./src/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _package_src_index_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../package/src/index.js */"./package/src/index.js"); - -_package_src_index_js__WEBPACK_IMPORTED_MODULE_0_.a.a; -_package_src_index_js__WEBPACK_IMPORTED_MODULE_0_.a.aa.aa; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./src/index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/reexport-all-as/expected/main.js b/crates/rspack/tests/tree-shaking/reexport-all-as/expected/main.js deleted file mode 100644 index 60000a022b1..00000000000 --- a/crates/rspack/tests/tree-shaking/reexport-all-as/expected/main.js +++ /dev/null @@ -1,42 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./package/autogen/a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - function a() {} - function dddd() {} -}, -"./package/autogen/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return _a__WEBPACK_IMPORTED_MODULE_0_; } -}); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"./package/autogen/a.js"); - - - -}, -"./package/src/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _autogen_index__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../autogen/index */"./package/autogen/index.js"); -__webpack_require__.es(_autogen_index__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, -"./src/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _package_src_index_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ../package/src/index.js */"./package/src/index.js"); - -_package_src_index_js__WEBPACK_IMPORTED_MODULE_0_.a.a; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./src/index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/reexport_default_as/expected/main.js b/crates/rspack/tests/tree-shaking/reexport_default_as/expected/main.js deleted file mode 100644 index e82a1b13a20..00000000000 --- a/crates/rspack/tests/tree-shaking/reexport_default_as/expected/main.js +++ /dev/null @@ -1,32 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return test; } -}); -function test() {} -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Select': function() { return _bar__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _bar__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./bar */"./bar.js"); - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -(0, _foo__WEBPACK_IMPORTED_MODULE_0_.Select)(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/reexport_entry_elimination/expected/main.js b/crates/rspack/tests/tree-shaking/reexport_entry_elimination/expected/main.js deleted file mode 100644 index 205a254e0cf..00000000000 --- a/crates/rspack/tests/tree-shaking/reexport_entry_elimination/expected/main.js +++ /dev/null @@ -1,43 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'b': function() { return _b_js__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _b_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./b.js */"./b.js"); - - -}, -"./b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _c_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./c.js */"./c.js"); - -var __WEBPACK_DEFAULT_EXPORT__ = 2000 + _c_js__WEBPACK_IMPORTED_MODULE_0_["default"]; -}, -"./c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -var __WEBPACK_DEFAULT_EXPORT__ = 10; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); - -_a_js__WEBPACK_IMPORTED_MODULE_0_.b; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rename-export-from-import/expected/main.js b/crates/rspack/tests/tree-shaking/rename-export-from-import/expected/main.js deleted file mode 100644 index ec083c2f8cd..00000000000 --- a/crates/rspack/tests/tree-shaking/rename-export-from-import/expected/main.js +++ /dev/null @@ -1,34 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'q': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_.question; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_.q; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'question': function() { return question; } -}); - const answer = "1"; - const question = "2"; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports-function-argument/expected/main.js b/crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports-function-argument/expected/main.js deleted file mode 100644 index e7494d84e39..00000000000 --- a/crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports-function-argument/expected/main.js +++ /dev/null @@ -1,32 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; }, - 'bar': function() { return bar; } -}); -var foo = function() { - return 42; -}; -var __WEBPACK_DEFAULT_EXPORT__ = foo; - function bar() { - return contrivedExample(foo); -} -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -var answer = (0, _foo__WEBPACK_IMPORTED_MODULE_0_["default"])(); -var somethingElse = (0, _foo__WEBPACK_IMPORTED_MODULE_0_.bar)(); -console.log(answer); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports/expected/main.js b/crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports/expected/main.js deleted file mode 100644 index 654f1ddec4f..00000000000 --- a/crates/rspack/tests/tree-shaking/rollup-unmodified-default-exports/expected/main.js +++ /dev/null @@ -1,32 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -var Foo = function() { - console.log("side effect"); - this.isFoo = true; -}; -var __WEBPACK_DEFAULT_EXPORT__ = Foo; -Foo.prototype = { - answer: function() { - return 42; - } -}; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -var foo = new _foo__WEBPACK_IMPORTED_MODULE_0_["default"](); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rollup-unused-called-import/expected/main.js b/crates/rspack/tests/tree-shaking/rollup-unused-called-import/expected/main.js deleted file mode 100644 index b8bd01004b7..00000000000 --- a/crates/rspack/tests/tree-shaking/rollup-unused-called-import/expected/main.js +++ /dev/null @@ -1,37 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./dead.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -function __WEBPACK_DEFAULT_EXPORT__(){ - return "dead"; -} -}, -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _dead__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dead */"./dead.js"); - -function __WEBPACK_DEFAULT_EXPORT__(){ - return "foo"; -} - function foodead() { - return "foo" + /* "./dead" unused */null(); -} -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -assert.equal((0, _foo__WEBPACK_IMPORTED_MODULE_0_["default"])(), "foo"); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rollup-unused-default-exports/expected/main.js b/crates/rspack/tests/tree-shaking/rollup-unused-default-exports/expected/main.js deleted file mode 100644 index 67be18f12e4..00000000000 --- a/crates/rspack/tests/tree-shaking/rollup-unused-default-exports/expected/main.js +++ /dev/null @@ -1,30 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'foo': function() { return foo; } -}); - var foo = { - value: 1 -}; -function mutate(obj) { - obj.value += 1; - return obj; -} -var __WEBPACK_DEFAULT_EXPORT__ = mutate(foo); -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); - -assert.equal(_foo__WEBPACK_IMPORTED_MODULE_0_.foo.value, 2); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rollup-unused-inner-functions-and-classes/expected/main.js b/crates/rspack/tests/tree-shaking/rollup-unused-inner-functions-and-classes/expected/main.js deleted file mode 100644 index 3b6dd7ba881..00000000000 --- a/crates/rspack/tests/tree-shaking/rollup-unused-inner-functions-and-classes/expected/main.js +++ /dev/null @@ -1,63 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _stuff__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./stuff */"./stuff.js"); - -(0, _stuff__WEBPACK_IMPORTED_MODULE_0_.bar)(); -var f = (0, _stuff__WEBPACK_IMPORTED_MODULE_0_.baz)(); -f(); -function getClass() { - class MyClass { - } - class UnusedInnerClass1 { - } - return MyClass; -} -class UnusedClass { -} -console.log(getClass().name); -}, -"./stuff.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'bar': function() { return bar; }, - 'baz': function() { return Baz; } -}); - function foo() { - console.log("outer foo"); -} - function bar() { - console.log("outer bar"); -} - function bog() { - console.log("outer bog"); -} - function boo() { - console.log("outer boo"); -} -function Baz() { - function foo() { - console.log("inner foo"); - } - function bar() { - console.log("inner bar"); - } - function bog() { - console.log("inner bog"); - } - function boo() { - console.log("inner boo"); - } - return bar(), bog; -} - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/rollup-unused-var/expected/main.js b/crates/rspack/tests/tree-shaking/rollup-unused-var/expected/main.js deleted file mode 100644 index af94a25bd4c..00000000000 --- a/crates/rspack/tests/tree-shaking/rollup-unused-var/expected/main.js +++ /dev/null @@ -1,26 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./foo.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'foo': function() { return foo; } -}); -var foo = "lol"; -var bar = "wut"; -var baz = bar || foo; - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo.js */"./foo.js"); - -console.log(_foo_js__WEBPACK_IMPORTED_MODULE_0_.foo); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/side-effects-analyzed/expected/main.js b/crates/rspack/tests/tree-shaking/side-effects-analyzed/expected/main.js deleted file mode 100644 index e84908372f3..00000000000 --- a/crates/rspack/tests/tree-shaking/side-effects-analyzed/expected/main.js +++ /dev/null @@ -1,36 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'something': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.something)(); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -function __WEBPACK_DEFAULT_EXPORT__(){} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/side-effects-export-default-expr/expected/main.js b/crates/rspack/tests/tree-shaking/side-effects-export-default-expr/expected/main.js deleted file mode 100644 index 8c9450a0238..00000000000 --- a/crates/rspack/tests/tree-shaking/side-effects-export-default-expr/expected/main.js +++ /dev/null @@ -1,25 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'b': function() { return b; } -}); - -var __WEBPACK_DEFAULT_EXPORT__ = /* "./lib" unused */null; - const b = 1; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_.b; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/side-effects-flagged-only/expected/main.js b/crates/rspack/tests/tree-shaking/side-effects-flagged-only/expected/main.js deleted file mode 100644 index fa7a74d9293..00000000000 --- a/crates/rspack/tests/tree-shaking/side-effects-flagged-only/expected/main.js +++ /dev/null @@ -1,44 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'something': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); -/* harmony import */var _src_a__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./src/a */"./src/a.js"); - - -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.something)(); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -function __WEBPACK_DEFAULT_EXPORT__(){} -}, -"./src/a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -var __WEBPACK_DEFAULT_EXPORT__ = (()=>{ - console.log(""); -}); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/side-effects-prune/expected/main.js b/crates/rspack/tests/tree-shaking/side-effects-prune/expected/main.js deleted file mode 100644 index 13767f2ed52..00000000000 --- a/crates/rspack/tests/tree-shaking/side-effects-prune/expected/main.js +++ /dev/null @@ -1,35 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); -__webpack_require__.es(_lib__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - - // export { - // result as test - // } -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.something)(); // a; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'something': function() { return something; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/side-effects-two/expected/main.js b/crates/rspack/tests/tree-shaking/side-effects-two/expected/main.js deleted file mode 100644 index add9fa6ab4a..00000000000 --- a/crates/rspack/tests/tree-shaking/side-effects-two/expected/main.js +++ /dev/null @@ -1,38 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'something': function() { return _lib__WEBPACK_IMPORTED_MODULE_0_["default"]; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - // export { - // result as test - // } -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.something)(); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -function __WEBPACK_DEFAULT_EXPORT__(){} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/simple-namespace-access/expected/main.js b/crates/rspack/tests/tree-shaking/simple-namespace-access/expected/main.js deleted file mode 100644 index d705eb5b99a..00000000000 --- a/crates/rspack/tests/tree-shaking/simple-namespace-access/expected/main.js +++ /dev/null @@ -1,47 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _maths_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./maths.js */"./maths.js"); -/* TREE-SHAKING */ -console.log(_maths_js__WEBPACK_IMPORTED_MODULE_0_.xxx.test); -console.log(_maths_js__WEBPACK_IMPORTED_MODULE_0_.square); -}, -"./maths.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'xxx': function() { return _test_js__WEBPACK_IMPORTED_MODULE_0_; }, - 'square': function() { return square; } -}); -/* harmony import */var _test_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./test.js */"./test.js"); -// maths.js -// This function isn't used anywhere, so -// Rollup excludes it from the bundle... - function square(x) { - return x * x; -} -// This function gets included - function cube(x) { - // rewrite this as `square( x ) * x` - // and see what happens! - return x * x * x; -} - -}, -"./test.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'test': function() { return test; } -}); - function test() {} - function ccc() {} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/static-class/expected/main.js b/crates/rspack/tests/tree-shaking/static-class/expected/main.js deleted file mode 100644 index d7d7c639418..00000000000 --- a/crates/rspack/tests/tree-shaking/static-class/expected/main.js +++ /dev/null @@ -1,45 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -/* harmony import */var _b_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./b.js */"./b.js"); - - class Test { - static c = (0, _b_js__WEBPACK_IMPORTED_MODULE_0_.bb)(); - static test() { - _b_js__WEBPACK_IMPORTED_MODULE_0_.bb; - } -} -class Result { - static test() { - /* "./b.js" unused */null; - } -} - const a = 3; -}, -"./b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'bb': function() { return bb; } -}); - const bb = 2; - const cc = 3; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); - -_a_js__WEBPACK_IMPORTED_MODULE_0_.a; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/transitive-bailout/expected/main.js b/crates/rspack/tests/tree-shaking/transitive-bailout/expected/main.js deleted file mode 100644 index 8fbb394c1c4..00000000000 --- a/crates/rspack/tests/tree-shaking/transitive-bailout/expected/main.js +++ /dev/null @@ -1,38 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; }, - 'b': function() { return b; } -}); - const a = 3; - const b = 3; -}, -"./answer.js": function (__unused_webpack_module, exports, __webpack_require__) { -const res = __webpack_require__(/* ./lib.js */"./lib.js"); -exports.test = function() { - res; -}; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _answer__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./answer */"./answer.js"); - -_answer__WEBPACK_IMPORTED_MODULE_0_.test; -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); -__webpack_require__.es(_a_js__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/transitive_side_effects_when_analyze/expected/main.js b/crates/rspack/tests/tree-shaking/transitive_side_effects_when_analyze/expected/main.js deleted file mode 100644 index ebe16a1792f..00000000000 --- a/crates/rspack/tests/tree-shaking/transitive_side_effects_when_analyze/expected/main.js +++ /dev/null @@ -1,30 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -/* harmony import */var _side_effects_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./side-effects.js */"./side-effects.js"); -/* harmony import */var _side_effects_js__WEBPACK_IMPORTED_MODULE_1__default = /*#__PURE__*/__webpack_require__.n(_side_effects_js__WEBPACK_IMPORTED_MODULE_1_); - - - const a = 3; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -_app__WEBPACK_IMPORTED_MODULE_0_.a; -}, -"./side-effects.js": function (__unused_webpack_module, exports, __webpack_require__) { -console.log("side effect"); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/tree-shaking-false-with-side-effect-true/expected/main.js b/crates/rspack/tests/tree-shaking/tree-shaking-false-with-side-effect-true/expected/main.js deleted file mode 100644 index f43c9d80720..00000000000 --- a/crates/rspack/tests/tree-shaking/tree-shaking-false-with-side-effect-true/expected/main.js +++ /dev/null @@ -1,34 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./ b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'b': function() { return b; } -}); - const b = 3; -}, -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 3; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); -/* harmony import */var _b_js__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./ b.js */"./ b.js"); - - -_a_js__WEBPACK_IMPORTED_MODULE_0_.a; -_b_js__WEBPACK_IMPORTED_MODULE_1_.b; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/bar_js.js b/crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/bar_js.js deleted file mode 100644 index 603a7efc37b..00000000000 --- a/crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/bar_js.js +++ /dev/null @@ -1,11 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["bar_js"], { -"./bar.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return test; } -}); -function test() {} -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/main.js b/crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/main.js deleted file mode 100644 index f6d11786f2a..00000000000 --- a/crates/rspack/tests/tree-shaking/tree-shaking-interop/expected/main.js +++ /dev/null @@ -1,34 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -__webpack_require__.el(/* ./bar */"./bar.js").then(__webpack_require__.bind(__webpack_require__, /* ./bar */"./bar.js")).then((mod)=>{ - console.log(mod); -}); - const a = "a"; -exports.test = 30; -}, -"./foo.js": function (module, exports, __webpack_require__) { -{ - const res = __webpack_require__(/* ./a */"./a.js"); - module.exports = res; -} // export default function () {} -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./foo */"./foo.js"); -/* harmony import */var _foo__WEBPACK_IMPORTED_MODULE_0__default = /*#__PURE__*/__webpack_require__.n(_foo__WEBPACK_IMPORTED_MODULE_0_); - -_foo__WEBPACK_IMPORTED_MODULE_0__default(); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/lib_js.js b/crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/lib_js.js deleted file mode 100644 index 192e05cd7d7..00000000000 --- a/crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/lib_js.js +++ /dev/null @@ -1,25 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["lib_js"], { -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _test__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./test */"./test.js"); - -function myanswer() { - _test__WEBPACK_IMPORTED_MODULE_0_["default"]; -} -var __WEBPACK_DEFAULT_EXPORT__ = myanswer; -}, -"./test.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -function test() {} -var __WEBPACK_DEFAULT_EXPORT__ = test; -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/main.js b/crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/main.js deleted file mode 100644 index 0e23e0d1639..00000000000 --- a/crates/rspack/tests/tree-shaking/tree-shaking-lazy-import/expected/main.js +++ /dev/null @@ -1,25 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'answer': function() { return answer; } -}); - const answer = 30; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -const a = test(()=>__webpack_require__.el(/* ./lib */"./lib.js").then(__webpack_require__.bind(__webpack_require__, /* ./lib */"./lib.js"))); -(0, _app__WEBPACK_IMPORTED_MODULE_0_.answer)(); -a; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/ts-target-es5/expected/main.js b/crates/rspack/tests/tree-shaking/ts-target-es5/expected/main.js deleted file mode 100644 index 064a397f006..00000000000 --- a/crates/rspack/tests/tree-shaking/ts-target-es5/expected/main.js +++ /dev/null @@ -1,508 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"../../../../../node_modules/@swc/helpers/esm/_async_to_generator.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - '_': function() { return _async_to_generator; } -}); -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - if (info.done) resolve(value); - else Promise.resolve(value).then(_next, _throw); -} - function _async_to_generator(fn) { - return function() { - var self = this, args = arguments; - return new Promise(function(resolve, reject) { - var gen = fn.apply(self, args); - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - _next(undefined); - }); - }; -} - -}, -"../../../../../node_modules/@swc/helpers/esm/_ts_generator.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - '_': function() { return tslib__WEBPACK_IMPORTED_MODULE_0_.__generator; } -}); -/* harmony import */var tslib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* tslib */"../../../../../node_modules/tslib/tslib.es6.js"); - -}, -"../../../../../node_modules/tslib/tslib.es6.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - '__generator': function() { return __generator; } -}); -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || ({ - __proto__: [] - }) instanceof Array && function(d, b) { - d.__proto__ = b; - } || function(d, b) { - for(var p in b)if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; - }; - return extendStatics(d, b); -}; - function __extends(d, b) { - if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { - this.constructor = d; - } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for(var s, i = 1, n = arguments.length; i < n; i++){ - s = arguments[i]; - for(var p in s)if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); -}; - function __rest(s, e) { - var t = {}; - for(var p in s)if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") { - for(var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++)if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; - } - return t; -} - function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; -} - function __param(paramIndex, decorator) { - return function(target, key) { - decorator(target, key, paramIndex); - }; -} - function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { - if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); - return f; - } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for(var i = decorators.length - 1; i >= 0; i--){ - var context = {}; - for(var p in contextIn)context[p] = p === "access" ? {} : contextIn[p]; - for(var p in contextIn.access)context.access[p] = contextIn.access[p]; - context.addInitializer = function(f) { - if (done) throw new TypeError("Cannot add initializers after decoration has completed"); - extraInitializers.push(accept(f || null)); - }; - var result = (0, decorators[i])(kind === "accessor" ? { - get: descriptor.get, - set: descriptor.set - } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.push(_); - } else if (_ = accept(result)) { - if (kind === "field") initializers.push(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -} - function __runInitializers(thisArg, initializers, value) { - var useValue = arguments.length > 2; - for(var i = 0; i < initializers.length; i++)value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - return useValue ? value : void 0; -} - function __propKey(x) { - return typeof x === "symbol" ? x : "".concat(x); -} - function __setFunctionName(f, name, prefix) { - if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; - return Object.defineProperty(f, "name", { - configurable: true, - value: prefix ? "".concat(prefix, " ", name) : name - }); -} - function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); -} - function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - function __generator(thisArg, body) { - var _ = { - label: 0, - sent: function() { - if (t[0] & 1) throw t[1]; - return t[1]; - }, - trys: [], - ops: [] - }, f, y, t, g; - return g = { - next: verb(0), - "throw": verb(1), - "return": verb(2) - }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { - return this; - }), g; - function verb(n) { - return function(v) { - return step([ - n, - v - ]); - }; - } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while(g && (g = 0, op[0] && (_ = 0)), _)try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [ - op[0] & 2, - t.value - ]; - switch(op[0]){ - case 0: - case 1: - t = op; - break; - case 4: - _.label++; - return { - value: op[1], - done: false - }; - case 5: - _.label++; - y = op[1]; - op = [ - 0 - ]; - continue; - case 7: - op = _.ops.pop(); - _.trys.pop(); - continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { - _ = 0; - continue; - } - if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { - _.label = op[1]; - break; - } - if (op[0] === 6 && _.label < t[1]) { - _.label = t[1]; - t = op; - break; - } - if (t && _.label < t[2]) { - _.label = t[2]; - _.ops.push(op); - break; - } - if (t[2]) _.ops.pop(); - _.trys.pop(); - continue; - } - op = body.call(thisArg, _); - } catch (e) { - op = [ - 6, - e - ]; - y = 0; - } finally{ - f = t = 0; - } - if (op[0] & 5) throw op[1]; - return { - value: op[0] ? op[1] : void 0, - done: true - }; - } -} - var __createBinding = Object.create ? function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = { - enumerable: true, - get: function() { - return m[k]; - } - }; - Object.defineProperty(o, k2, desc); -} : function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -}; - function __exportStar(m, o) { - for(var p in m)if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); -} - function __values(o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function() { - if (o && i >= o.length) o = void 0; - return { - value: o && o[i++], - done: !o - }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); -} - function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while((n === void 0 || n-- > 0) && !(r = i.next()).done)ar.push(r.value); - } catch (error) { - e = { - error: error - }; - } finally{ - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } finally{ - if (e) throw e.error; - } - } - return ar; -} -/** @deprecated */ function __spread() { - for(var ar = [], i = 0; i < arguments.length; i++)ar = ar.concat(__read(arguments[i])); - return ar; -} -/** @deprecated */ function __spreadArrays() { - for(var s = 0, i = 0, il = arguments.length; i < il; i++)s += arguments[i].length; - for(var r = Array(s), k = 0, i = 0; i < il; i++)for(var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)r[k] = a[j]; - return r; -} - function __spreadArray(to, from, pack) { - if (pack || arguments.length === 2) { - for(var i = 0, l = from.length, ar; i < l; i++)if (ar || !(i in from)) { - if (!ar) ar = Array.prototype.slice.call(from, 0, i); - ar[i] = from[i]; - } - } - return to.concat(ar || Array.prototype.slice.call(from)); -} - function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i; - function verb(n) { - if (g[n]) i[n] = function(v) { - return new Promise(function(a, b) { - q.push([ - n, - v, - a, - b - ]) > 1 || resume(n, v); - }); - }; - } - function resume(n, v) { - try { - step(g[n](v)); - } catch (e) { - settle(q[0][3], e); - } - } - function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f, v) { - if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); - } -} - function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function(e) { - throw e; - }), verb("return"), i[Symbol.iterator] = function() { - return this; - }, i; - function verb(n, f) { - i[n] = o[n] ? function(v) { - return (p = !p) ? { - value: __await(o[n](v)), - done: false - } : f ? f(v) : v; - } : f; - } -} - function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { - return this; - }, i); - function verb(n) { - i[n] = o[n] && function(v) { - return new Promise(function(resolve, reject) { - v = o[n](v), settle(resolve, reject, v.done, v.value); - }); - }; - } - function settle(resolve, reject, d, v) { - Promise.resolve(v).then(function(v) { - resolve({ - value: v, - done: d - }); - }, reject); - } -} - function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) Object.defineProperty(cooked, "raw", { - value: raw - }); - else cooked.raw = raw; - return cooked; -} -var __setModuleDefault = Object.create ? function(o, v) { - Object.defineProperty(o, "default", { - enumerable: true, - value: v - }); -} : function(o, v) { - o["default"] = v; -}; - function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) { - for(var k in mod)if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; -} - function __importDefault(mod) { - return mod && mod.__esModule ? mod : { - default: mod - }; -} - function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; -} - function __classPrivateFieldIn(state, receiver) { - if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); - return typeof state === "function" ? receiver === state : state.has(receiver); -} -}, -"./index.ts": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'test': function() { return test; } -}); -/* harmony import */var _swc_helpers_async_to_generator__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* @swc/helpers/_/_async_to_generator */"../../../../../node_modules/@swc/helpers/esm/_async_to_generator.js"); -/* harmony import */var _swc_helpers_ts_generator__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* @swc/helpers/_/_ts_generator */"../../../../../node_modules/@swc/helpers/esm/_ts_generator.js"); - - - function test() { - return _test.apply(this, arguments); -} -function _test() { - _test = (0, _swc_helpers_async_to_generator__WEBPACK_IMPORTED_MODULE_0_._)(function() { - return (0, _swc_helpers_ts_generator__WEBPACK_IMPORTED_MODULE_1_._)(this, function(_state) { - return [ - 2 - ]; - }); - }); - return _test.apply(this, arguments); -} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.ts")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/var-function-expr/expected/main.js b/crates/rspack/tests/tree-shaking/var-function-expr/expected/main.js deleted file mode 100644 index ad5af26e97c..00000000000 --- a/crates/rspack/tests/tree-shaking/var-function-expr/expected/main.js +++ /dev/null @@ -1,43 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./app.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'app': function() { return app; } -}); -/* harmony import */var _lib__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./lib */"./lib.js"); - - var app = function() { - _lib__WEBPACK_IMPORTED_MODULE_0_.result; -}; - var app2 = ()=>{ - /* "./lib" unused */null; -}; - var app4 = (0, _lib__WEBPACK_IMPORTED_MODULE_0_.something)('app4'), app5 = 10000; - var app3 = (0, _lib__WEBPACK_IMPORTED_MODULE_0_.something)('app3'); -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _app__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./app */"./app.js"); - -(0, _app__WEBPACK_IMPORTED_MODULE_0_.app)(); -}, -"./lib.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'result': function() { return result; }, - 'something': function() { return something; } -}); - const secret = "888"; - const result = 20000; - const something = function() {}; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-inner-graph-export-default-named/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-inner-graph-export-default-named/expected/main.js deleted file mode 100644 index e2a1c3cdae8..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-inner-graph-export-default-named/expected/main.js +++ /dev/null @@ -1,184 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return abc; } -}); -/* harmony import */var _dep_a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dep?a */"./dep.js?a"); - -function abc() { - return _dep_a__WEBPACK_IMPORTED_MODULE_0_.x; -} -}, -"./b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _dep_b__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dep?b */"./dep.js?b"); - -function abc() { - return /* "./dep?b" unused */null; -} -}, -"./c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _dep_c__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dep?c */"./dep.js?c"); - -function abc() { - return _dep_c__WEBPACK_IMPORTED_MODULE_0_.x; -} -abc(); -}, -"./d.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return def; } -}); -/* harmony import */var _dep_d__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dep?d */"./dep.js?d"); - -class def { - method() { - return _dep_d__WEBPACK_IMPORTED_MODULE_0_.x; - } -} -}, -"./dep.js?a": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return x; }, - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const x = "x"; -var __WEBPACK_DEFAULT_EXPORT__ = true; -}, -"./dep.js?b": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const x = "x"; -var __WEBPACK_DEFAULT_EXPORT__ = false; -}, -"./dep.js?c": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return x; }, - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const x = "x"; -var __WEBPACK_DEFAULT_EXPORT__ = true; -}, -"./dep.js?d": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return x; }, - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const x = "x"; -var __WEBPACK_DEFAULT_EXPORT__ = true; -}, -"./dep.js?e": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const x = "x"; -var __WEBPACK_DEFAULT_EXPORT__ = false; -}, -"./dep.js?f": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return x; }, - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); - const x = "x"; -var __WEBPACK_DEFAULT_EXPORT__ = true; -}, -"./e.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _dep_e__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dep?e */"./dep.js?e"); - -class def { - method() { - return /* "./dep?e" unused */null; - } -} -}, -"./f.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _dep_f__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./dep?f */"./dep.js?f"); - -class def { - method() { - return _dep_f__WEBPACK_IMPORTED_MODULE_0_.x; - } -} -new def().method(); -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"./a.js"); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b */"./b.js"); -/* harmony import */var _c__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./c */"./c.js"); -/* harmony import */var _d__WEBPACK_IMPORTED_MODULE_3_ = __webpack_require__(/* ./d */"./d.js"); -/* harmony import */var _e__WEBPACK_IMPORTED_MODULE_4_ = __webpack_require__(/* ./e */"./e.js"); -/* harmony import */var _f__WEBPACK_IMPORTED_MODULE_5_ = __webpack_require__(/* ./f */"./f.js"); -/* harmony import */var _dep_a__WEBPACK_IMPORTED_MODULE_6_ = __webpack_require__(/* ./dep?a */"./dep.js?a"); -/* harmony import */var _dep_b__WEBPACK_IMPORTED_MODULE_7_ = __webpack_require__(/* ./dep?b */"./dep.js?b"); -/* harmony import */var _dep_c__WEBPACK_IMPORTED_MODULE_8_ = __webpack_require__(/* ./dep?c */"./dep.js?c"); -/* harmony import */var _dep_d__WEBPACK_IMPORTED_MODULE_9_ = __webpack_require__(/* ./dep?d */"./dep.js?d"); -/* harmony import */var _dep_e__WEBPACK_IMPORTED_MODULE_10_ = __webpack_require__(/* ./dep?e */"./dep.js?e"); -/* harmony import */var _dep_f__WEBPACK_IMPORTED_MODULE_11_ = __webpack_require__(/* ./dep?f */"./dep.js?f"); - - - - - - - - - - - - -it("should generate valid code", ()=>{ - expect((0, _a__WEBPACK_IMPORTED_MODULE_0_["default"])()).toBe("x"); - expect(new (0, _d__WEBPACK_IMPORTED_MODULE_3_["default"])().method()).toBe("x"); -}); -it("a should be used", ()=>{ - expect(_dep_a__WEBPACK_IMPORTED_MODULE_6_["default"]).toBe(true); -}); -it("b should be unused", ()=>{ - expect(_dep_b__WEBPACK_IMPORTED_MODULE_7_["default"]).toBe(false); -}); -it("c should be used", ()=>{ - expect(_dep_c__WEBPACK_IMPORTED_MODULE_8_["default"]).toBe(true); -}); -it("d should be used", ()=>{ - expect(_dep_d__WEBPACK_IMPORTED_MODULE_9_["default"]).toBe(true); -}); -it("e should be unused", ()=>{ - expect(_dep_e__WEBPACK_IMPORTED_MODULE_10_["default"]).toBe(false); -}); -it("f should be used", ()=>{ - expect(_dep_f__WEBPACK_IMPORTED_MODULE_11_["default"]).toBe(true); -}); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-inner-graph-switch/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-inner-graph-switch/expected/main.js deleted file mode 100644 index 3d5ff8dd7f9..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-inner-graph-switch/expected/main.js +++ /dev/null @@ -1,91 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./import-module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'test': function() { return test; } -}); -/* harmony import */var _module__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./module */"./module.js"); - - function test() { - (0, _module__WEBPACK_IMPORTED_MODULE_0_["default"])({ - type: "inline" - }); -} -}, -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -it("should generate correct code when pure expressions are in dead branches", ()=>{ - __webpack_require__(/* ./import-module */"./import-module.js").test(); - return Promise.all([ - __webpack_require__.el(/* ./some-module */"./some-module.js").then(__webpack_require__.bind(__webpack_require__, /* ./some-module */"./some-module.js")), - __webpack_require__.el(/* ./chunk */"./chunk.js").then(__webpack_require__.bind(__webpack_require__, /* ./chunk */"./chunk.js")) - ]); -}); -}, -"./module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _some_module__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./some-module */"./some-module.js"); - -function getType(obj) { - return obj.type; -} -// Local functions -function doSomethingWithBlock(obj) { - return _some_module__WEBPACK_IMPORTED_MODULE_0_.Block.doSomething(obj); -} -function doSomethingWithInline(obj) { - return _some_module__WEBPACK_IMPORTED_MODULE_0_.Inline.doSomething(obj); -} -function doSomethingWithDocument(obj) { - return _some_module__WEBPACK_IMPORTED_MODULE_0_.Document.doSomething(obj); -} -// Exported functions -function doSomething(obj) { - const type = getType(obj); - switch(type){ - case "document": - return doSomethingWithDocument(obj); - case "block": - return doSomethingWithBlock(obj); - case "inline": - return doSomethingWithInline(obj); - default: - throw new Error(); - } -} -function useDocument(obj) { - return doSomethingWithDocument(obj); -} - -var __WEBPACK_DEFAULT_EXPORT__ = doSomething; -}, -"./some-module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'Block': function() { return Block; }, - 'Inline': function() { return Inline; }, - 'Document': function() { return Document; } -}); -class Block { - static doSomething() {} -} -class Inline { - static doSomething() {} -} -class Document { - static doSomething() {} -} - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/chunk_js.js b/crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/chunk_js.js deleted file mode 100644 index 4628f86d19b..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/chunk_js.js +++ /dev/null @@ -1,9 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["chunk_js"], { -"./chunk.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _inner__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./inner */"./inner.js"); - -}, - -}]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/main.js deleted file mode 100644 index 832e9674944..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-innergraph-circular/expected/main.js +++ /dev/null @@ -1,81 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _inner__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./inner */"./inner.js"); -/* harmony import */var _module__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./module */"./module.js"); - - -it("export should be unused when only unused functions use it", ()=>{ - expect((0, _module__WEBPACK_IMPORTED_MODULE_1_.y)("a")).toBe("okBAA"); - expect(_inner__WEBPACK_IMPORTED_MODULE_0_.exportAUsed).toBe(true); - expect(_inner__WEBPACK_IMPORTED_MODULE_0_.exportBUsed).toBe(true); - expect(_inner__WEBPACK_IMPORTED_MODULE_0_.exportCUsed).toBe(false); - return __webpack_require__.el(/* ./chunk */"./chunk.js").then(__webpack_require__.bind(__webpack_require__, /* ./chunk */"./chunk.js")); -}); -}, -"./inner.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'A': function() { return A; }, - 'B': function() { return B; }, - 'exportAUsed': function() { return exportAUsed; }, - 'exportBUsed': function() { return exportBUsed; }, - 'exportCUsed': function() { return exportCUsed; } -}); - function A(s) { - return s + "A"; -} - function B(s) { - return s + "B"; -} - function C(s) { - return s + "C"; -} - const exportAUsed = true; - const exportBUsed = true; - const exportCUsed = false; -}, -"./module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'y': function() { return y; } -}); -/* harmony import */var _inner__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./inner */"./inner.js"); - -function x(type) { - switch(type){ - case "a": - return withA("b"); - case "b": - return withB("c"); - case "c": - return "ok"; - } -} -function y(v) { - return withA(v); -} -function withA(v) { - const value = x(v); - return (0, _inner__WEBPACK_IMPORTED_MODULE_0_.A)(value); -} -function withB(v) { - const value = x(v); - return (0, _inner__WEBPACK_IMPORTED_MODULE_0_.B)(value); -} -function withC(v) { - const value = x(v); - return /* "./inner" unused */null(value); -} - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-innergraph-circular2/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-innergraph-circular2/expected/main.js deleted file mode 100644 index c26a7a91a7c..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-innergraph-circular2/expected/main.js +++ /dev/null @@ -1,132 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _module__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./module */"./module.js"); - -it("should be able to handle circular referenced", ()=>{ - expect((0, _module__WEBPACK_IMPORTED_MODULE_0_.x)()).toEqual([ - _module__WEBPACK_IMPORTED_MODULE_0_.y, - _module__WEBPACK_IMPORTED_MODULE_0_.z - ]); - const [_a, b, c, d] = (0, _module__WEBPACK_IMPORTED_MODULE_0_.a)(); - expect(b()).toEqual([ - _module__WEBPACK_IMPORTED_MODULE_0_.a, - b, - c, - d - ]); - expect(c()).toEqual([ - _module__WEBPACK_IMPORTED_MODULE_0_.a, - b, - c, - d - ]); - expect(d()).toEqual([ - _module__WEBPACK_IMPORTED_MODULE_0_.a, - b, - c, - d - ]); - const [f2, f4] = (0, _module__WEBPACK_IMPORTED_MODULE_0_.f3)(); - const [f1, _f3] = f2(); - expect(_f3).toBe(_module__WEBPACK_IMPORTED_MODULE_0_.f3); - expect((0, _module__WEBPACK_IMPORTED_MODULE_0_.f3)()).toEqual(f1()); - expect(f2()).toEqual(f4()); -}); -}, -"./module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return x; }, - 'y': function() { return y; }, - 'z': function() { return z; }, - 'a': function() { return a; }, - 'f3': function() { return f3; } -}); -function x() { - return [ - y, - z - ]; -} -function y() { - return [ - x, - z - ]; -} -function z() { - return [ - x, - y - ]; -} - -function a() { - return [ - a, - b, - c, - d - ]; -} -function b() { - return [ - a, - b, - c, - d - ]; -} -function c() { - return [ - a, - b, - c, - d - ]; -} -function d() { - return [ - a, - b, - c, - d - ]; -} - -function f1() { - return [ - f2, - f4 - ]; -} -function f2() { - return [ - f1, - f3 - ]; -} -function f3() { - return [ - f2, - f4 - ]; -} -function f4() { - return [ - f1, - f3 - ]; -} - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-innergraph-no-side-effects/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-innergraph-no-side-effects/expected/main.js deleted file mode 100644 index 181a50214a9..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-innergraph-no-side-effects/expected/main.js +++ /dev/null @@ -1,39 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -it("should be able to load package without side effects where modules are unused", ()=>{ - __webpack_require__(/* ./module */"./module.js"); -}); -}, -"./module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; }, - 'test': function() { return test; } -}); -/* harmony import */var _package__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./package */"./package/index.js"); - -var __WEBPACK_DEFAULT_EXPORT__ = _package__WEBPACK_IMPORTED_MODULE_0_.a; - function test() {} -}, -"./package/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - - function a() { - return 42; -} - function b() { - return /* "./unusedModule" unused */null; -} -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-innergraph-try-globals/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-innergraph-try-globals/expected/main.js deleted file mode 100644 index 221c30e5dfb..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-innergraph-try-globals/expected/main.js +++ /dev/null @@ -1,47 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./import-module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _module__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./module */"./module.js"); - -expect(_module__WEBPACK_IMPORTED_MODULE_0_.ok).toBe(true); -expect(_module__WEBPACK_IMPORTED_MODULE_0_.ok2).toBe(true); -}, -"./index.js": function (__unused_webpack_module, exports, __webpack_require__) { -it("should not threat globals as pure", ()=>{ - __webpack_require__(/* ./import-module */"./import-module.js"); -}); -}, -"./module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'ok': function() { return ok; }, - 'ok2': function() { return ok2; } -}); -try { - var x = NOT_DEFINED; - var y = x; - var ok = false; -} catch (e) { - var yep = true; - var ok = yep; -} -try { - const b = a; - var c = b; - const a = 42; - var ok2 = false; - eval(""); // TODO terser has a bug and incorrectly remove this code, eval opts out -} catch (e) { - var ok2 = true; -} - -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-reexport-namespace-and-default/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-reexport-namespace-and-default/expected/main.js deleted file mode 100644 index 7609fa8b653..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-reexport-namespace-and-default/expected/main.js +++ /dev/null @@ -1,98 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _package1_script__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./package1/script */"./package1/script.js"); -/* harmony import */var _package1_script2__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./package1/script2 */"./package1/script2.js"); -/* harmony import */var _package2_script__WEBPACK_IMPORTED_MODULE_3_ = __webpack_require__(/* ./package2/script */"./package2/script.js"); - - - -it("should load module correctly", ()=>{ - __webpack_require__(/* ./module */"./module.js"); -}); -// if (process.env.NODE_ENV === "production") { -it("default export should be unused", ()=>{ - expect(_package1_script__WEBPACK_IMPORTED_MODULE_1_.exportDefaultUsed).toBe(false); - expect(_package1_script2__WEBPACK_IMPORTED_MODULE_2_.exportDefaultUsed).toBe(false); -}); -// } -it("default export should be used", ()=>{ - expect(_package2_script__WEBPACK_IMPORTED_MODULE_3_.exportDefaultUsed).toBe(true); -}); -}, -"./module.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'mod': function() { return mod; } -}); -/* harmony import */var _package1_script__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./package1/script */"./package1/script.js"); -/* harmony import */var _package2_script__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./package2/script */"./package2/script.js"); - - - const mod = _package2_script__WEBPACK_IMPORTED_MODULE_1_["default"]; -}, -"./package1/script.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'exportDefaultUsed': function() { return exportDefaultUsed; } -}); -/* harmony import */var _script1__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./script1 */"./package1/script1.js"); -__webpack_require__.es(_script1__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -var __WEBPACK_DEFAULT_EXPORT__ = /* "./script1" unused */null; - - const exportDefaultUsed = false; -}, -"./package1/script1.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _script2__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./script2 */"./package1/script2.js"); -__webpack_require__.es(_script2__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -var __WEBPACK_DEFAULT_EXPORT__ = 1; -}, -"./package1/script2.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'exportDefaultUsed': function() { return exportDefaultUsed; } -}); - -function __WEBPACK_DEFAULT_EXPORT__(){ - return /* "./script3" unused */null; -} - - const exportDefaultUsed = false; -}, -"./package2/script.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; }, - 'exportDefaultUsed': function() { return exportDefaultUsed; } -}); -/* harmony import */var _script1__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./script1 */"./package2/script1.js"); -__webpack_require__.es(_script1__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); - -var __WEBPACK_DEFAULT_EXPORT__ = _script1__WEBPACK_IMPORTED_MODULE_0_["default"]; - - const exportDefaultUsed = true; -}, -"./package2/script1.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -var __WEBPACK_DEFAULT_EXPORT__ = 1; -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-side-effects-all-used/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-side-effects-all-used/expected/main.js deleted file mode 100644 index 802bdbec4b0..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-side-effects-all-used/expected/main.js +++ /dev/null @@ -1,103 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"../node_modules/pmodule/a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); -var a = "a"; -var b = "b"; -var c = "c"; - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_0_.track)("a.js"); -}, -"../node_modules/pmodule/b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'z': function() { return _c__WEBPACK_IMPORTED_MODULE_0_.z; }, - 'x': function() { return x; } -}); -/* harmony import */var _c__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./c */"../node_modules/pmodule/c.js"); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); -var x = "x"; -var y = "y"; - - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_1_.track)("b.js"); -}, -"../node_modules/pmodule/c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'z': function() { return z; } -}); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); -var z = "z"; - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_0_.track)("c.js"); -}, -"../node_modules/pmodule/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return _b__WEBPACK_IMPORTED_MODULE_1_.x; }, - 'z': function() { return _b__WEBPACK_IMPORTED_MODULE_1_.z; }, - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _a__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a */"../node_modules/pmodule/a.js"); -__webpack_require__.es(_a__WEBPACK_IMPORTED_MODULE_0_, __webpack_exports__); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b */"../node_modules/pmodule/b.js"); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); - - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_2_.track)("index.js"); -var __WEBPACK_DEFAULT_EXPORT__ = "def"; -}, -"../node_modules/pmodule/tracker.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'track': function() { return track; }, - 'log': function() { return log; } -}); - function track(file) { - log.push(file); - log.sort(); -} - var log = []; - function reset() { - log.length = 0; -} -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var pmodule_tracker__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* pmodule/tracker */"../node_modules/pmodule/tracker.js"); -/* harmony import */var pmodule__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* pmodule */"../node_modules/pmodule/index.js"); - - - -pmodule__WEBPACK_IMPORTED_MODULE_1_["default"].should.be.eql("def"); -pmodule__WEBPACK_IMPORTED_MODULE_1_.a.should.be.eql("a"); -pmodule__WEBPACK_IMPORTED_MODULE_1_.x.should.be.eql("x"); -pmodule__WEBPACK_IMPORTED_MODULE_1_.z.should.be.eql("z"); -pmodule_tracker__WEBPACK_IMPORTED_MODULE_0_.log.should.be.eql([ - "a.js", - "b.js", - "c.js", - "index.js" -]); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/webpack-side-effects-simple-unused/expected/main.js b/crates/rspack/tests/tree-shaking/webpack-side-effects-simple-unused/expected/main.js deleted file mode 100644 index c209f3164ec..00000000000 --- a/crates/rspack/tests/tree-shaking/webpack-side-effects-simple-unused/expected/main.js +++ /dev/null @@ -1,85 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"../node_modules/pmodule/b.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'z': function() { return _c__WEBPACK_IMPORTED_MODULE_0_.z; }, - 'x': function() { return x; } -}); -/* harmony import */var _c__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./c */"../node_modules/pmodule/c.js"); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); -var x = "x"; -var y = "y"; - - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_1_.track)("b.js"); -}, -"../node_modules/pmodule/c.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'z': function() { return z; } -}); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); -var z = "z"; - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_0_.track)("c.js"); -}, -"../node_modules/pmodule/index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'x': function() { return _b__WEBPACK_IMPORTED_MODULE_1_.x; }, - 'z': function() { return _b__WEBPACK_IMPORTED_MODULE_1_.z; }, - 'default': function() { return __WEBPACK_DEFAULT_EXPORT__; } -}); -/* harmony import */var _b__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./b */"../node_modules/pmodule/b.js"); -/* harmony import */var _tracker__WEBPACK_IMPORTED_MODULE_2_ = __webpack_require__(/* ./tracker */"../node_modules/pmodule/tracker.js"); - - - -(0, _tracker__WEBPACK_IMPORTED_MODULE_2_.track)("index.js"); -var __WEBPACK_DEFAULT_EXPORT__ = "def"; -}, -"../node_modules/pmodule/tracker.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'track': function() { return track; }, - 'log': function() { return log; } -}); - function track(file) { - log.push(file); - log.sort(); -} - var log = []; - function reset() { - log.length = 0; -} -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var pmodule_tracker__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* pmodule/tracker */"../node_modules/pmodule/tracker.js"); -/* harmony import */var pmodule__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* pmodule */"../node_modules/pmodule/index.js"); - - - -pmodule__WEBPACK_IMPORTED_MODULE_1_["default"].should.be.eql("def"); -pmodule__WEBPACK_IMPORTED_MODULE_1_.x.should.be.eql("x"); -pmodule__WEBPACK_IMPORTED_MODULE_1_.z.should.be.eql("z"); -pmodule_tracker__WEBPACK_IMPORTED_MODULE_0_.log.should.be.eql([ - "b.js", - "c.js", - "index.js" -]); -}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file diff --git a/crates/rspack/tests/tree-shaking/with-assets/expected/main.js b/crates/rspack/tests/tree-shaking/with-assets/expected/main.js deleted file mode 100644 index b96b64788cc..00000000000 --- a/crates/rspack/tests/tree-shaking/with-assets/expected/main.js +++ /dev/null @@ -1,28 +0,0 @@ -(self['webpackChunkwebpack'] = self['webpackChunkwebpack'] || []).push([["main"], { -"./a.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -__webpack_require__.d(__webpack_exports__, { - 'a': function() { return a; } -}); - const a = 3; -}, -"./index.js": function (__unused_webpack_module, __webpack_exports__, __webpack_require__) { -'use strict'; -__webpack_require__.r(__webpack_exports__); -/* harmony import */var _a_js__WEBPACK_IMPORTED_MODULE_0_ = __webpack_require__(/* ./a.js */"./a.js"); -/* harmony import */var _a_svg__WEBPACK_IMPORTED_MODULE_1_ = __webpack_require__(/* ./a.svg */"./a.svg"); - - -_a_js__WEBPACK_IMPORTED_MODULE_0_.a; -_a_svg__WEBPACK_IMPORTED_MODULE_1_; -}, -"./a.svg": function (module, exports, __webpack_require__) { -module.exports = "data:image/svg+xml;base64,";}, - -},function(__webpack_require__) { -var __webpack_exec__ = function(moduleId) { return __webpack_require__(__webpack_require__.s = moduleId) } -var __webpack_exports__ = (__webpack_exec__("./index.js")); - -} -]); \ No newline at end of file From 2008c03216053ee6fd831a6fc1c03d7d3fef7b89 Mon Sep 17 00:00:00 2001 From: IWANABETHATGUY Date: Tue, 12 Sep 2023 22:31:51 +0800 Subject: [PATCH 13/49] feat: combine three tree shaking related plugin, and add corresponding configuration. (#4147) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: 🤖 compile them together * chore: 🤖 finish flag dependency usage * chore: 🤖 update * chore: 🤖 remove temp file * chore: 🤖 renmae * chore: 🤖 recovefr * chore: 🤖 update types * chore: 🤖 update defaults * chore: 🤖 update snapshot * chore: 🤖 update rspack test * chore: 🤖 tree shaking mode * chore: 🤖 update tree shaking * chore: 🤖 fix compile error * chore: 🤖 update options * chore: 🤖 lint * chore: 🤖 lint * chore: 🤖 first test * chore: 🤖 add new hooks * chore: 🤖 refactor * chore: 🤖 lint * chore: 🤖 update basic test * chore: 🤖 recover --- crates/node_binding/binding.d.ts | 3 ++ .../rspack_binding_options/src/options/mod.rs | 10 ++++ .../src/options/raw_experiments.rs | 2 + .../src/options/raw_optimization.rs | 6 ++- .../rspack_core/src/compiler/compilation.rs | 8 +++ crates/rspack_core/src/exports_info.rs | 14 +++++ crates/rspack_core/src/module.rs | 2 +- .../src/options/compiler_options.rs | 4 ++ crates/rspack_core/src/options/experiments.rs | 1 + .../rspack_core/src/options/optimizations.rs | 50 ++++++++++++++++++ crates/rspack_core/src/plugin/api.rs | 4 ++ .../rspack_core/src/plugin/plugin_driver.rs | 10 ++++ crates/rspack_loader_sass/tests/fixtures.rs | 2 + crates/rspack_loader_swc/tests/fixtures.rs | 2 + ...n.rs => flag_dependency_exports_plugin.rs} | 51 ++++++++++++++++--- ...gin.rs => flag_dependency_usage_plugin.rs} | 23 +++++++-- .../src/plugin/mod.rs | 9 ++-- .../src/plugin/side_effects_flag_plugin.rs | 14 +++-- crates/rspack_testing/src/test_config.rs | 10 +++- packages/rspack/src/config/adapter.ts | 14 +++-- packages/rspack/src/config/defaults.ts | 3 ++ packages/rspack/src/config/zod.ts | 7 ++- packages/rspack/tests/Defaults.unittest.ts | 12 ++++- packages/rspack/tests/Stats.test.ts | 1 + .../__snapshots__/Defaults.unittest.ts.snap | 3 ++ 25 files changed, 235 insertions(+), 30 deletions(-) rename crates/rspack_plugin_javascript/src/plugin/{provided_exports_plugin.rs => flag_dependency_exports_plugin.rs} (83%) rename crates/rspack_plugin_javascript/src/plugin/{flag_usage_plugin.rs => flag_dependency_usage_plugin.rs} (94%) diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index b5d89c61635..340d732b1bf 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -828,6 +828,8 @@ export interface RawOptimizationOptions { removeAvailableModules: boolean removeEmptyChunks: boolean sideEffects: string + usedExports: string + providedExports: boolean realContentHash: boolean } @@ -953,6 +955,7 @@ export interface RawResolveOptions { export interface RawRspackFuture { newResolver: boolean + newTreeshaking: boolean } export interface RawRuleSetCondition { diff --git a/crates/rspack_binding_options/src/options/mod.rs b/crates/rspack_binding_options/src/options/mod.rs index f52d70be30b..21ee026e89a 100644 --- a/crates/rspack_binding_options/src/options/mod.rs +++ b/crates/rspack_binding_options/src/options/mod.rs @@ -3,6 +3,7 @@ use rspack_core::{ BoxPlugin, CompilerOptions, Context, DevServerOptions, Devtool, Experiments, IncrementalRebuild, IncrementalRebuildMakeState, ModuleOptions, ModuleType, OutputOptions, PluginExt, }; +use rspack_plugin_javascript::{FlagDependencyExportsPlugin, FlagDependencyUsagePlugin}; use serde::Deserialize; mod raw_builtins; @@ -158,6 +159,15 @@ impl RawOptionsApply for RawOptions { plugins.push(rspack_ids::NamedChunkIdsPlugin::new(None, None).boxed()); + if experiments.rspack_future.new_treeshaking { + if optimization.provided_exports { + plugins.push(FlagDependencyExportsPlugin::default().boxed()); + } + if optimization.used_exports.is_enable() { + plugins.push(FlagDependencyUsagePlugin::default().boxed()); + } + } + // Notice the plugin need to be placed after SplitChunksPlugin if optimization.remove_empty_chunks { plugins.push(rspack_plugin_remove_empty_chunks::RemoveEmptyChunksPlugin.boxed()); diff --git a/crates/rspack_binding_options/src/options/raw_experiments.rs b/crates/rspack_binding_options/src/options/raw_experiments.rs index aab912c8761..df516d8a6d5 100644 --- a/crates/rspack_binding_options/src/options/raw_experiments.rs +++ b/crates/rspack_binding_options/src/options/raw_experiments.rs @@ -15,6 +15,7 @@ pub struct RawIncrementalRebuild { #[napi(object)] pub struct RawRspackFuture { pub new_resolver: bool, + pub new_treeshaking: bool, } #[derive(Deserialize, Debug, Default)] @@ -33,6 +34,7 @@ impl From for RspackFuture { fn from(value: RawRspackFuture) -> Self { Self { new_resolver: value.new_resolver, + new_treeshaking: value.new_treeshaking, } } } diff --git a/crates/rspack_binding_options/src/options/raw_optimization.rs b/crates/rspack_binding_options/src/options/raw_optimization.rs index e7af9e67e61..2b777936311 100644 --- a/crates/rspack_binding_options/src/options/raw_optimization.rs +++ b/crates/rspack_binding_options/src/options/raw_optimization.rs @@ -1,6 +1,6 @@ use better_scoped_tls::scoped_tls; use napi_derive::napi; -use rspack_core::{Optimization, PluginExt, SideEffectOption}; +use rspack_core::{Optimization, PluginExt, SideEffectOption, UsedExports}; use rspack_error::internal_error; use rspack_ids::{ DeterministicChunkIdsPlugin, DeterministicModuleIdsPlugin, NamedChunkIdsPlugin, @@ -23,6 +23,8 @@ pub struct RawOptimizationOptions { pub remove_available_modules: bool, pub remove_empty_chunks: bool, pub side_effects: String, + pub used_exports: String, + pub provided_exports: bool, pub real_content_hash: bool, } @@ -71,6 +73,8 @@ impl RawOptionsApply for RawOptimizationOptions { remove_available_modules: self.remove_available_modules, remove_empty_chunks: self.remove_empty_chunks, side_effects: SideEffectOption::from(self.side_effects.as_str()), + provided_exports: self.provided_exports, + used_exports: UsedExports::from(self.used_exports.as_str()), }) } } diff --git a/crates/rspack_core/src/compiler/compilation.rs b/crates/rspack_core/src/compiler/compilation.rs index d1677c7aad9..88634bd7247 100644 --- a/crates/rspack_core/src/compiler/compilation.rs +++ b/crates/rspack_core/src/compiler/compilation.rs @@ -359,6 +359,7 @@ impl Compilation { MakeParam::ForceBuildModules(std::mem::take(&mut self.make_failed_module)); let make_failed_dependencies = MakeParam::ForceBuildDeps(std::mem::take(&mut self.make_failed_dependencies)); + self .update_module_graph(vec![param, make_failed_module, make_failed_dependencies]) .await @@ -1144,12 +1145,19 @@ impl Compilation { let start = logger.time("finish modules"); plugin_driver.finish_modules(self).await?; logger.time_end(start); + Ok(()) } #[instrument(name = "compilation:seal", skip_all)] pub async fn seal(&mut self, plugin_driver: SharedPluginDriver) -> Result<()> { let logger = self.get_logger("rspack.Compilation"); + + let start = logger.time("optimize dependencies"); + // https://github.com/webpack/webpack/blob/d15c73469fd71cf98734685225250148b68ddc79/lib/Compilation.js#L2812-L2814 + while plugin_driver.optimize_dependencies(self).await?.is_some() {} + logger.time_end(start); + let start = logger.time("create chunks"); use_code_splitting_cache(self, |compilation| async { build_chunk_graph(compilation)?; diff --git a/crates/rspack_core/src/exports_info.rs b/crates/rspack_core/src/exports_info.rs index 8630eb0f6a6..613d5a11fcd 100644 --- a/crates/rspack_core/src/exports_info.rs +++ b/crates/rspack_core/src/exports_info.rs @@ -1200,3 +1200,17 @@ pub fn process_export_info( referenced_export.push(prefix); } } + +#[allow(clippy::dbg_macro)] +pub fn debug_exports_info(module_graph: &ModuleGraph) { + for mgm in module_graph.module_graph_modules().values() { + dbg!(&mgm.module_identifier); + let exports_info_id = mgm.exports; + let exports_info = module_graph.get_exports_info_by_id(&exports_info_id); + dbg!(&exports_info); + for id in exports_info.exports.values() { + let export_info = module_graph.get_export_info_by_id(id); + dbg!(&export_info); + } + } +} diff --git a/crates/rspack_core/src/module.rs b/crates/rspack_core/src/module.rs index 7d8a142059a..8223c032e7e 100644 --- a/crates/rspack_core/src/module.rs +++ b/crates/rspack_core/src/module.rs @@ -49,7 +49,7 @@ pub struct BuildInfo { pub need_create_require: bool, } -#[derive(Debug, Default, Clone, Hash)] +#[derive(Debug, Default, Clone, Hash, PartialEq, Eq)] pub enum BuildMetaExportsType { #[default] Unset, diff --git a/crates/rspack_core/src/options/compiler_options.rs b/crates/rspack_core/src/options/compiler_options.rs index 02aa8b6118b..22d9c4f40d4 100644 --- a/crates/rspack_core/src/options/compiler_options.rs +++ b/crates/rspack_core/src/options/compiler_options.rs @@ -38,4 +38,8 @@ impl CompilerOptions { pub fn is_incremental_rebuild_emit_asset_enabled(&self) -> bool { self.experiments.incremental_rebuild.emit_asset } + + pub fn is_new_tree_shaking(&self) -> bool { + self.experiments.rspack_future.new_treeshaking + } } diff --git a/crates/rspack_core/src/options/experiments.rs b/crates/rspack_core/src/options/experiments.rs index c5afa9cce27..1ffb1886910 100644 --- a/crates/rspack_core/src/options/experiments.rs +++ b/crates/rspack_core/src/options/experiments.rs @@ -24,6 +24,7 @@ impl IncrementalRebuildMakeState { #[derive(Debug, Default)] pub struct RspackFuture { pub new_resolver: bool, + pub new_treeshaking: bool, } #[derive(Debug, Default)] diff --git a/crates/rspack_core/src/options/optimizations.rs b/crates/rspack_core/src/options/optimizations.rs index aa9d309e7f4..53016153a33 100644 --- a/crates/rspack_core/src/options/optimizations.rs +++ b/crates/rspack_core/src/options/optimizations.rs @@ -44,9 +44,59 @@ impl SideEffectOption { } } +#[derive(Debug, Clone, Copy, Default)] +pub enum UsedExports { + #[default] + False, + True, + Global, +} + +impl From<&str> for UsedExports { + fn from(value: &str) -> Self { + match value { + "true" => Self::True, + "global" => Self::Global, + _ => Self::False, + } + } +} + +impl UsedExports { + pub fn is_enable(&self) -> bool { + matches!(self, Self::Global | Self::True) + } + + /// Returns `true` if the used exports is [`False`]. + /// + /// [`False`]: UsedExports::False + #[must_use] + pub fn is_false(&self) -> bool { + matches!(self, Self::False) + } + + /// Returns `true` if the used exports is [`True`]. + /// + /// [`True`]: UsedExports::True + #[must_use] + pub fn is_true(&self) -> bool { + matches!(self, Self::True) + } + + /// Returns `true` if the used exports is [`Global`]. + /// + /// [`Global`]: UsedExports::Global + #[must_use] + pub fn is_global(&self) -> bool { + matches!(self, Self::Global) + } +} + #[derive(Debug)] pub struct Optimization { pub remove_available_modules: bool, pub remove_empty_chunks: bool, pub side_effects: SideEffectOption, + pub provided_exports: bool, + pub used_exports: UsedExports, } diff --git a/crates/rspack_core/src/plugin/api.rs b/crates/rspack_core/src/plugin/api.rs index 3ff4cd10040..8973374b337 100644 --- a/crates/rspack_core/src/plugin/api.rs +++ b/crates/rspack_core/src/plugin/api.rs @@ -370,6 +370,10 @@ pub trait Plugin: Debug + Send + Sync { Ok(()) } + async fn optimize_dependencies(&self, _compilation: &mut Compilation) -> Result> { + Ok(None) + } + async fn optimize_tree(&self, _compilation: &mut Compilation) -> Result<()> { Ok(()) } diff --git a/crates/rspack_core/src/plugin/plugin_driver.rs b/crates/rspack_core/src/plugin/plugin_driver.rs index 3c54761e27b..fc28fa7fc9a 100644 --- a/crates/rspack_core/src/plugin/plugin_driver.rs +++ b/crates/rspack_core/src/plugin/plugin_driver.rs @@ -499,6 +499,16 @@ impl PluginDriver { Ok(()) } + #[instrument(name = "plugin:optimize_dependencies", skip_all)] + pub async fn optimize_dependencies(&self, compilation: &mut Compilation) -> Result> { + for plugin in &self.plugins { + if let Some(t) = plugin.optimize_dependencies(compilation).await? { + return Ok(Some(t)); + }; + } + Ok(None) + } + #[instrument(name = "plugin:optimize_tree", skip_all)] pub async fn optimize_tree(&self, compilation: &mut Compilation) -> Result<()> { for plugin in &self.plugins { diff --git a/crates/rspack_loader_sass/tests/fixtures.rs b/crates/rspack_loader_sass/tests/fixtures.rs index 67a8e4b12f7..0318454ebf8 100644 --- a/crates/rspack_loader_sass/tests/fixtures.rs +++ b/crates/rspack_loader_sass/tests/fixtures.rs @@ -87,6 +87,8 @@ async fn loader_test(actual: impl AsRef, expected: impl AsRef) { remove_available_modules: false, remove_empty_chunks: true, side_effects: SideEffectOption::False, + provided_exports: Default::default(), + used_exports: Default::default(), }, profile: false, }), diff --git a/crates/rspack_loader_swc/tests/fixtures.rs b/crates/rspack_loader_swc/tests/fixtures.rs index de50e0c32d2..7fbedabb2f8 100644 --- a/crates/rspack_loader_swc/tests/fixtures.rs +++ b/crates/rspack_loader_swc/tests/fixtures.rs @@ -87,6 +87,8 @@ async fn loader_test(actual: impl AsRef, expected: impl AsRef) { remove_available_modules: false, remove_empty_chunks: true, side_effects: SideEffectOption::False, + provided_exports: Default::default(), + used_exports: Default::default(), }, profile: false, }), diff --git a/crates/rspack_plugin_javascript/src/plugin/provided_exports_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs similarity index 83% rename from crates/rspack_plugin_javascript/src/plugin/provided_exports_plugin.rs rename to crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs index 418d9018209..8d15d7c5f2b 100644 --- a/crates/rspack_plugin_javascript/src/plugin/provided_exports_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/flag_dependency_exports_plugin.rs @@ -2,20 +2,22 @@ use std::collections::hash_map::Entry; use std::collections::VecDeque; use rspack_core::{ - DependencyId, ExportInfoProvided, ExportNameOrSpec, ExportsInfoId, ExportsOfExportsSpec, - ExportsSpec, ModuleGraph, ModuleGraphConnection, ModuleIdentifier, + BuildMetaExportsType, Compilation, DependencyId, ExportInfoProvided, ExportNameOrSpec, + ExportsInfoId, ExportsOfExportsSpec, ExportsSpec, ModuleGraph, ModuleGraphConnection, + ModuleIdentifier, Plugin, }; +use rspack_error::Result; use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet}; use swc_core::ecma::atoms::JsWord; -pub struct ProvidedExportsPlugin<'a> { +struct FlagDependencyExportsProxy<'a> { mg: &'a mut ModuleGraph, changed: bool, current_module_id: ModuleIdentifier, dependencies: HashMap>, } -impl<'a> ProvidedExportsPlugin<'a> { +impl<'a> FlagDependencyExportsProxy<'a> { pub fn new(mg: &'a mut ModuleGraph) -> Self { Self { mg, @@ -27,18 +29,43 @@ impl<'a> ProvidedExportsPlugin<'a> { pub fn apply(&mut self) { let mut q = VecDeque::new(); + + // take the ownership of module_identifier_to_module_graph_module to avoid borrow ref and + // mut ref of `ModuleGraph` at the same time + let module_graph_modules = + std::mem::take(&mut self.mg.module_identifier_to_module_graph_module); + for mgm in module_graph_modules.values() { + let exports_id = mgm.exports; + let is_module_without_exports = if let Some(ref build_meta) = mgm.build_meta { + build_meta.exports_type == BuildMetaExportsType::Unset + } else { + true + } && { + let exports_info = self.mg.get_exports_info_by_id(&exports_id); + let other_exports_info_id = exports_info.other_exports_info; + let other_exports_info = self.mg.get_export_info_by_id(&other_exports_info_id); + other_exports_info.provided.is_some() + }; + + // TODO: mem cache + exports_id.set_has_provide_info(self.mg); + q.push_back(mgm.module_identifier); + if is_module_without_exports { + exports_id.set_unknown_exports_provided(self.mg, false, None, None, None, None); + } + } + self.mg.module_identifier_to_module_graph_module = module_graph_modules; + while let Some(module_id) = q.pop_back() { self.changed = false; self.current_module_id = module_id; let mut exports_specs_from_dependencies: HashMap = HashMap::default(); self.process_dependencies_block(module_id, &mut exports_specs_from_dependencies); - // I use this trick because of rustc borrow rules, it is safe becuase dependency provide plugin is sync, there are no other methods using it at the same time. let exports_info_id = self.mg.get_exports_info(&module_id).id; for (dep_id, exports_spec) in exports_specs_from_dependencies.into_iter() { self.process_exports_spec(dep_id, exports_spec, exports_info_id); } - // Swap it back if self.changed { self.notify_dependencies(&mut q); } @@ -287,3 +314,15 @@ pub struct DefaultExportInfo<'a> { from: Option<&'a ModuleGraphConnection>, priority: Option, } + +#[derive(Debug, Default)] +pub struct FlagDependencyExportsPlugin; + +#[async_trait::async_trait] +impl Plugin for FlagDependencyExportsPlugin { + async fn finish_modules(&self, compilation: &mut Compilation) -> Result<()> { + let mut proxy = FlagDependencyExportsProxy::new(&mut compilation.module_graph); + proxy.apply(); + Ok(()) + } +} diff --git a/crates/rspack_plugin_javascript/src/plugin/flag_usage_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/flag_dependency_usage_plugin.rs similarity index 94% rename from crates/rspack_plugin_javascript/src/plugin/flag_usage_plugin.rs rename to crates/rspack_plugin_javascript/src/plugin/flag_dependency_usage_plugin.rs index 7cf5a905d75..f1b8d17f132 100644 --- a/crates/rspack_plugin_javascript/src/plugin/flag_usage_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/flag_dependency_usage_plugin.rs @@ -3,23 +3,24 @@ use std::collections::VecDeque; use rspack_core::{ is_exports_object_referenced, is_no_exports_referenced, BuildMetaExportsType, Compilation, - ConnectionState, DependencyId, ExportsInfoId, ExtendedReferencedExport, ModuleIdentifier, + ConnectionState, DependencyId, ExportsInfoId, ExtendedReferencedExport, ModuleIdentifier, Plugin, ReferencedExport, RuntimeSpec, UsageState, }; +use rspack_error::Result; use rspack_identifier::IdentifierMap; use rustc_hash::FxHashMap as HashMap; use crate::utils::join_jsword; #[allow(unused)] -pub struct FlagDependencyUsagePlugin<'a> { +pub struct FlagDependencyUsagePluginProxy<'a> { global: bool, compilation: &'a mut Compilation, exports_info_module_map: HashMap, } #[allow(unused)] -impl<'a> FlagDependencyUsagePlugin<'a> { +impl<'a> FlagDependencyUsagePluginProxy<'a> { pub fn new(global: bool, compilation: &'a mut Compilation) -> Self { Self { global, @@ -53,7 +54,7 @@ impl<'a> FlagDependencyUsagePlugin<'a> { } } // TODO: compilation.globalEntry.dependencies, we don't have now https://github.com/webpack/webpack/blob/3f71468514ae2f179ff34c837ce82fcc8f97e24c/lib/FlagDependencyUsagePlugin.js#L328-L330 - _ = std::mem::replace(&mut self.compilation.entries, entries); + self.compilation.entries = entries; while let Some((module_id, runtime)) = q.pop_front() { self.process_module(module_id, runtime, false, &mut q); @@ -335,3 +336,17 @@ impl<'a> FlagDependencyUsagePlugin<'a> { } } } + +#[derive(Debug, Default)] +pub struct FlagDependencyUsagePlugin; + +#[async_trait::async_trait] +impl Plugin for FlagDependencyUsagePlugin { + async fn optimize_dependencies(&self, compilation: &mut Compilation) -> Result> { + // TODO: `global` is always `true`, until we finished runtime optimization. + let mut proxy = FlagDependencyUsagePluginProxy::new(true, compilation); + proxy.apply(); + println!("optimize_dependencies"); + Ok(None) + } +} diff --git a/crates/rspack_plugin_javascript/src/plugin/mod.rs b/crates/rspack_plugin_javascript/src/plugin/mod.rs index 4d82856d693..44630fd9721 100644 --- a/crates/rspack_plugin_javascript/src/plugin/mod.rs +++ b/crates/rspack_plugin_javascript/src/plugin/mod.rs @@ -1,12 +1,14 @@ pub mod api_plugin; -pub mod flag_usage_plugin; +mod flag_dependency_exports_plugin; +mod flag_dependency_usage_plugin; pub mod impl_plugin_for_js_plugin; pub mod infer_async_modules_plugin; -pub mod provided_exports_plugin; -pub mod side_effects_flag_plugin; +mod side_effects_flag_plugin; use std::hash::Hash; +pub use flag_dependency_exports_plugin::*; +pub use flag_dependency_usage_plugin::*; use rspack_core::rspack_sources::{BoxSource, ConcatSource, RawSource, SourceExt}; use rspack_core::{ ChunkUkey, Compilation, JsChunkHashArgs, PluginJsChunkHashHookOutput, RenderArgs, @@ -14,6 +16,7 @@ use rspack_core::{ }; use rspack_error::Result; use rspack_hash::RspackHash; +pub use side_effects_flag_plugin::*; use crate::runtime::{ render_chunk_init_fragments, render_chunk_modules, render_iife, render_runtime_modules, diff --git a/crates/rspack_plugin_javascript/src/plugin/side_effects_flag_plugin.rs b/crates/rspack_plugin_javascript/src/plugin/side_effects_flag_plugin.rs index a14f0e99210..cd00c175af2 100644 --- a/crates/rspack_plugin_javascript/src/plugin/side_effects_flag_plugin.rs +++ b/crates/rspack_plugin_javascript/src/plugin/side_effects_flag_plugin.rs @@ -1,12 +1,13 @@ +// use rspack_core::Plugin; +// use rspack_error::Result; use swc_core::common::{Span, Spanned, SyntaxContext, GLOBALS}; use swc_core::ecma::ast::*; use swc_core::ecma::utils::{ExprCtx, ExprExt}; use swc_core::ecma::visit::{noop_visit_type, Visit, VisitWith}; #[derive(Debug)] -pub struct SideEffectsFlagPlugin { +pub struct SideEffectsFlagPluginVisitor { unresolved_ctxt: SyntaxContext, - // module_identifier: ModuleIdentifier, side_effects_span: Option, is_top_level: bool, } @@ -22,7 +23,7 @@ impl SyntaxContextInfo { } } -impl SideEffectsFlagPlugin { +impl SideEffectsFlagPluginVisitor { pub fn new(mark_info: SyntaxContextInfo) -> Self { Self { unresolved_ctxt: mark_info.unresolved_ctxt, @@ -32,7 +33,7 @@ impl SideEffectsFlagPlugin { } } -impl Visit for SideEffectsFlagPlugin { +impl Visit for SideEffectsFlagPluginVisitor { noop_visit_type!(); fn visit_program(&mut self, node: &Program) { assert!(GLOBALS.is_set()); @@ -94,7 +95,7 @@ impl Visit for SideEffectsFlagPlugin { } } -impl SideEffectsFlagPlugin { +impl SideEffectsFlagPluginVisitor { /// If we find a stmt that has side effects, we will skip the rest of the stmts. /// And mark the module as having side effects. fn analyze_stmt_side_effects(&mut self, ele: &Stmt) { @@ -275,3 +276,6 @@ impl ClassKey for ClassMember { } } } + +#[derive(Debug, Default)] +pub struct SideEffectsFlagPlugin; diff --git a/crates/rspack_testing/src/test_config.rs b/crates/rspack_testing/src/test_config.rs index cc2720fe73f..5d589575783 100644 --- a/crates/rspack_testing/src/test_config.rs +++ b/crates/rspack_testing/src/test_config.rs @@ -68,7 +68,7 @@ fn default_optimization_chunk_ids() -> String { "named".to_string() } -fn default_optimization_side_effects() -> String { +fn default_optimization_false_string_lit() -> String { "false".to_string() } @@ -121,8 +121,12 @@ pub struct Optimization { pub module_ids: String, #[serde(default = "default_optimization_chunk_ids")] pub chunk_ids: String, - #[serde(default = "default_optimization_side_effects")] + #[serde(default = "default_optimization_false_string_lit")] pub side_effects: String, + #[serde(default = "true_by_default")] + pub provided_exports: bool, + #[serde(default = "default_optimization_false_string_lit")] + pub used_exports: String, } #[derive(Debug, JsonSchema, Deserialize)] @@ -436,6 +440,8 @@ impl TestConfig { remove_available_modules: self.optimization.remove_available_modules, remove_empty_chunks: self.optimization.remove_empty_chunks, side_effects: c::SideEffectOption::from(self.optimization.side_effects.as_str()), + provided_exports: self.optimization.provided_exports, + used_exports: c::UsedExports::from(self.optimization.used_exports.as_str()), }, profile: false, }; diff --git a/packages/rspack/src/config/adapter.ts b/packages/rspack/src/config/adapter.ts index f0b89d783b3..cae9ffb0a22 100644 --- a/packages/rspack/src/config/adapter.ts +++ b/packages/rspack/src/config/adapter.ts @@ -637,8 +637,10 @@ function getRawOptimization( !isNil(optimization.removeAvailableModules) && !isNil(optimization.removeEmptyChunks) && !isNil(optimization.sideEffects) && - !isNil(optimization.realContentHash), - "optimization.moduleIds, optimization.removeAvailableModules, optimization.removeEmptyChunks, optimization.sideEffects, optimization.realContentHash should not be nil after defaults" + !isNil(optimization.realContentHash) && + !isNil(optimization.providedExports) && + !isNil(optimization.usedExports), + "optimization.moduleIds, optimization.removeAvailableModules, optimization.removeEmptyChunks, optimization.sideEffects, optimization.realContentHash, optimization.providedExports, optimization.usedExports should not be nil after defaults" ); return { chunkIds: optimization.chunkIds, @@ -647,7 +649,9 @@ function getRawOptimization( removeAvailableModules: optimization.removeAvailableModules, removeEmptyChunks: optimization.removeEmptyChunks, sideEffects: String(optimization.sideEffects), - realContentHash: optimization.realContentHash + realContentHash: optimization.realContentHash, + usedExports: String(optimization.usedExports), + providedExports: optimization.providedExports }; } @@ -739,8 +743,10 @@ function getRawRspackFutureOptions( future: RspackFutureOptions ): RawRspackFuture { assert(!isNil(future.newResolver)); + assert(!isNil(future.newTreeshaking)); return { - newResolver: future.newResolver + newResolver: future.newResolver, + newTreeshaking: future.newTreeshaking }; } diff --git a/packages/rspack/src/config/defaults.ts b/packages/rspack/src/config/defaults.ts index d24bb093faa..bc96a436657 100644 --- a/packages/rspack/src/config/defaults.ts +++ b/packages/rspack/src/config/defaults.ts @@ -174,6 +174,7 @@ const applyExperimentsDefaults = ( D(experiments, "rspackFuture", {}); if (typeof experiments.rspackFuture === "object") { D(experiments.rspackFuture, "newResolver", false); + D(experiments.rspackFuture, "newTreeshaking", false); } }; @@ -666,6 +667,8 @@ const applyOptimizationDefaults = ( }); F(optimization, "chunkIds", (): "named" | "deterministic" => "named"); F(optimization, "sideEffects", () => (production ? true : "flag")); + D(optimization, "providedExports", true); + D(optimization, "usedExports", production); D(optimization, "runtimeChunk", false); D(optimization, "realContentHash", production); D(optimization, "minimize", production); diff --git a/packages/rspack/src/config/zod.ts b/packages/rspack/src/config/zod.ts index cab671dfae7..f9a2ebb6348 100644 --- a/packages/rspack/src/config/zod.ts +++ b/packages/rspack/src/config/zod.ts @@ -917,7 +917,9 @@ const optimization = z.strictObject({ removeAvailableModules: z.boolean().optional(), removeEmptyChunks: z.boolean().optional(), realContentHash: z.boolean().optional(), - sideEffects: z.enum(["flag"]).or(z.boolean()).optional() + sideEffects: z.enum(["flag"]).or(z.boolean()).optional(), + providedExports: z.boolean().optional(), + usedExports: z.enum(["global"]).or(z.boolean()).optional() }); export type Optimization = z.infer; //#endregion @@ -932,7 +934,8 @@ export type IncrementalRebuildOptions = z.infer< >; const rspackFutureOptions = z.strictObject({ - newResolver: z.boolean().optional() + newResolver: z.boolean().optional(), + newTreeshaking: z.boolean().optional() }); export type RspackFutureOptions = z.infer; diff --git a/packages/rspack/tests/Defaults.unittest.ts b/packages/rspack/tests/Defaults.unittest.ts index e6296e41230..b028ebd6094 100644 --- a/packages/rspack/tests/Defaults.unittest.ts +++ b/packages/rspack/tests/Defaults.unittest.ts @@ -112,8 +112,9 @@ describe("snapshots", () => { + "minimize": true, @@ ... @@ - "moduleIds": "named", - - "realContentHash": false, + "moduleIds": "deterministic", + @@ ... @@ + - "realContentHash": false, + "realContentHash": true, @@ ... @@ - "sideEffects": "flag", @@ -127,6 +128,9 @@ describe("snapshots", () => { - "minSize": 10000, + "minSize": 20000, @@ ... @@ + - "usedExports": false, + + "usedExports": true, + @@ ... @@ - "hash": false, + "hash": true, @@ ... @@ @@ -147,8 +151,9 @@ describe("snapshots", () => { + "minimize": true, @@ ... @@ - "moduleIds": "named", - - "realContentHash": false, + "moduleIds": "deterministic", + @@ ... @@ + - "realContentHash": false, + "realContentHash": true, @@ ... @@ - "sideEffects": "flag", @@ -162,6 +167,9 @@ describe("snapshots", () => { - "minSize": 10000, + "minSize": 20000, @@ ... @@ + - "usedExports": false, + + "usedExports": true, + @@ ... @@ - "hash": false, + "hash": true, @@ ... @@ diff --git a/packages/rspack/tests/Stats.test.ts b/packages/rspack/tests/Stats.test.ts index 7b9e671505d..e137424c586 100644 --- a/packages/rspack/tests/Stats.test.ts +++ b/packages/rspack/tests/Stats.test.ts @@ -144,6 +144,7 @@ describe("Stats", () => { module build task: X ms finish modules: X ms optimize dependencies: X ms + optimize dependencies: X ms create chunks: X ms optimize: X ms module ids: X ms diff --git a/packages/rspack/tests/__snapshots__/Defaults.unittest.ts.snap b/packages/rspack/tests/__snapshots__/Defaults.unittest.ts.snap index 728f86b31f8..b05d2676840 100644 --- a/packages/rspack/tests/__snapshots__/Defaults.unittest.ts.snap +++ b/packages/rspack/tests/__snapshots__/Defaults.unittest.ts.snap @@ -26,6 +26,7 @@ exports[`snapshots should have the correct base config 1`] = ` "newSplitChunks": true, "rspackFuture": { "newResolver": false, + "newTreeshaking": false, }, }, "externals": undefined, @@ -187,6 +188,7 @@ exports[`snapshots should have the correct base config 1`] = ` "minimize": false, "minimizer": [], "moduleIds": "named", + "providedExports": true, "realContentHash": false, "removeAvailableModules": true, "removeEmptyChunks": true, @@ -213,6 +215,7 @@ exports[`snapshots should have the correct base config 1`] = ` "minChunks": 1, "minSize": 10000, }, + "usedExports": false, }, "output": { "assetModuleFilename": "[hash][ext][query]", From c073f03d2d3bda6a6376725435a926175e704df4 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Wed, 13 Sep 2023 12:12:03 +0800 Subject: [PATCH 14/49] Release Packages:0.3.3 (#4172) Reelase Packages:0.3.3 Co-authored-by: github-actions[bot] --- crates/node_binding/package.json | 2 +- npm/darwin-arm64/package.json | 2 +- npm/darwin-x64/package.json | 2 +- npm/linux-x64-gnu/package.json | 2 +- npm/win32-x64-msvc/package.json | 2 +- package.json | 2 +- packages/create-rspack/package.json | 2 +- packages/rspack-cli/package.json | 2 +- packages/rspack-dev-client/package.json | 2 +- packages/rspack-dev-server/package.json | 2 +- packages/rspack-plugin-html/package.json | 2 +- packages/rspack-plugin-minify/package.json | 2 +- packages/rspack-plugin-node-polyfill/package.json | 2 +- packages/rspack-plugin-react-refresh/package.json | 2 +- packages/rspack/package.json | 2 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/crates/node_binding/package.json b/crates/node_binding/package.json index 21cff575349..96abab37381 100644 --- a/crates/node_binding/package.json +++ b/crates/node_binding/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/binding", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Node binding for rspack", "main": "binding.js", diff --git a/npm/darwin-arm64/package.json b/npm/darwin-arm64/package.json index 1ff4f4623b6..0773c3480e2 100644 --- a/npm/darwin-arm64/package.json +++ b/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/binding-darwin-arm64", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Node binding for rspack", "main": "rspack.darwin-arm64.node", diff --git a/npm/darwin-x64/package.json b/npm/darwin-x64/package.json index 488bec64304..aa00261bdbb 100644 --- a/npm/darwin-x64/package.json +++ b/npm/darwin-x64/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/binding-darwin-x64", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Node binding for rspack", "main": "rspack.darwin-x64.node", diff --git a/npm/linux-x64-gnu/package.json b/npm/linux-x64-gnu/package.json index b9f230c3a1a..1b450ff5fca 100644 --- a/npm/linux-x64-gnu/package.json +++ b/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/binding-linux-x64-gnu", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Node binding for rspack", "main": "rspack.linux-x64-gnu.node", diff --git a/npm/win32-x64-msvc/package.json b/npm/win32-x64-msvc/package.json index ed6f8f80cc7..2aa9fd3a38e 100644 --- a/npm/win32-x64-msvc/package.json +++ b/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/binding-win32-x64-msvc", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Node binding for rspack", "main": "rspack.win32-x64-msvc.node", diff --git a/package.json b/package.json index 084907596c3..904e7d34107 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "monorepo", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "A Fast Rust-based web bundler", "private": true, diff --git a/packages/create-rspack/package.json b/packages/create-rspack/package.json index 1fb2cb9f270..5b34939c537 100644 --- a/packages/create-rspack/package.json +++ b/packages/create-rspack/package.json @@ -1,6 +1,6 @@ { "name": "create-rspack", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "main": "index.js", "bin": { diff --git a/packages/rspack-cli/package.json b/packages/rspack-cli/package.json index 2d6f2eca4e4..87c6645773a 100644 --- a/packages/rspack-cli/package.json +++ b/packages/rspack-cli/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/cli", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "CLI for rspack", "bin": { diff --git a/packages/rspack-dev-client/package.json b/packages/rspack-dev-client/package.json index 9d3317c5d4e..bf7668698a2 100644 --- a/packages/rspack-dev-client/package.json +++ b/packages/rspack-dev-client/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/dev-client", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Development client for rspack", "scripts": { diff --git a/packages/rspack-dev-server/package.json b/packages/rspack-dev-server/package.json index 047bbdcfd1f..4e2eb599a89 100644 --- a/packages/rspack-dev-server/package.json +++ b/packages/rspack-dev-server/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/dev-server", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Development server for rspack", "main": "./dist/index.js", diff --git a/packages/rspack-plugin-html/package.json b/packages/rspack-plugin-html/package.json index 18ed78ce0c4..f5f83a17509 100644 --- a/packages/rspack-plugin-html/package.json +++ b/packages/rspack-plugin-html/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/plugin-html", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "HTML plugin for rspack", "main": "index.cjs", diff --git a/packages/rspack-plugin-minify/package.json b/packages/rspack-plugin-minify/package.json index 95af1e1d0b7..ce2ae58b7df 100644 --- a/packages/rspack-plugin-minify/package.json +++ b/packages/rspack-plugin-minify/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/plugin-minify", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Minify plugin for rspack", "main": "src/index.js", diff --git a/packages/rspack-plugin-node-polyfill/package.json b/packages/rspack-plugin-node-polyfill/package.json index 5754f26ca97..5a2e42c1bde 100644 --- a/packages/rspack-plugin-node-polyfill/package.json +++ b/packages/rspack-plugin-node-polyfill/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/plugin-node-polyfill", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "Node polyfill plugin for rspack", "main": "src/index.js", diff --git a/packages/rspack-plugin-react-refresh/package.json b/packages/rspack-plugin-react-refresh/package.json index 761f2ae2b66..35eb0870a91 100644 --- a/packages/rspack-plugin-react-refresh/package.json +++ b/packages/rspack-plugin-react-refresh/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/plugin-react-refresh", - "version": "0.3.2", + "version": "0.3.3", "license": "MIT", "description": "React refresh plugin for rspack", "main": "src/index.js", diff --git a/packages/rspack/package.json b/packages/rspack/package.json index d09ca72cf7d..10bf603ef24 100644 --- a/packages/rspack/package.json +++ b/packages/rspack/package.json @@ -1,6 +1,6 @@ { "name": "@rspack/core", - "version": "0.3.2", + "version": "0.3.3", "webpackVersion": "5.75.0", "license": "MIT", "description": "A Fast Rust-based Web Bundler", From b823393d335140cd737b2edb080dbb6f231bee4f Mon Sep 17 00:00:00 2001 From: lipp <489435760@qq.com> Date: Wed, 13 Sep 2023 11:42:50 +0800 Subject: [PATCH 15/49] feat: add externalsPresets webAsync target support (#4184) --- crates/node_binding/binding.d.ts | 16 +++++++ .../src/options/raw_builtins/mod.rs | 2 +- .../src/options/raw_external.rs | 1 + .../src/http_externals_plugin.rs | 48 +++++++++++++++++-- crates/rspack_testing/src/test_config.rs | 4 +- .../HttpExternalsRspackPlugin.ts | 5 +- packages/rspack/src/config/zod.ts | 1 + packages/rspack/src/rspackOptionsApply.ts | 6 ++- 8 files changed, 75 insertions(+), 8 deletions(-) diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index 340d732b1bf..7f4e7670c46 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -440,6 +440,13 @@ export interface JsStatsWarning { formatted: string } +export interface NodeFS { + writeFile: (...args: any[]) => any + removeFile: (...args: any[]) => any + mkdir: (...args: any[]) => any + mkdirp: (...args: any[]) => any +} + export interface PathData { filename?: string hash?: string @@ -727,6 +734,7 @@ export interface RawHtmlRspackPluginOptions { export interface RawHttpExternalsRspackPluginOptions { css: boolean + webAsync: boolean } export interface RawIncrementalRebuild { @@ -1054,3 +1062,11 @@ export function registerGlobalTrace(filter: string, layer: "chrome" | "logger", /** Builtin loader runner */ export function runBuiltinLoader(builtin: string, options: string | undefined | null, loaderContext: JsLoaderContext): Promise +export interface ThreadsafeNodeFS { + writeFile: (...args: any[]) => any + removeFile: (...args: any[]) => any + mkdir: (...args: any[]) => any + mkdirp: (...args: any[]) => any + removeDirAll: (...args: any[]) => any +} + diff --git a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs index 33d1e732436..50844ca53a1 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/mod.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/mod.rs @@ -152,7 +152,7 @@ impl RawOptionsApply for BuiltinPlugin { // rspack specific plugins BuiltinPluginName::HttpExternalsRspackPlugin => { let plugin_options = downcast_into::(self.options)?; - let plugin = http_externals_rspack_plugin(plugin_options.css); + let plugin = http_externals_rspack_plugin(plugin_options.css, plugin_options.web_async); plugins.push(plugin); } BuiltinPluginName::SwcJsMinimizerRspackPlugin => { diff --git a/crates/rspack_binding_options/src/options/raw_external.rs b/crates/rspack_binding_options/src/options/raw_external.rs index 06c6a0fced8..6f003e19813 100644 --- a/crates/rspack_binding_options/src/options/raw_external.rs +++ b/crates/rspack_binding_options/src/options/raw_external.rs @@ -21,6 +21,7 @@ use { #[napi(object)] pub struct RawHttpExternalsRspackPluginOptions { pub css: bool, + pub web_async: bool, } #[derive(Deserialize)] diff --git a/crates/rspack_plugin_externals/src/http_externals_plugin.rs b/crates/rspack_plugin_externals/src/http_externals_plugin.rs index e84c95529d7..11c2381f538 100644 --- a/crates/rspack_plugin_externals/src/http_externals_plugin.rs +++ b/crates/rspack_plugin_externals/src/http_externals_plugin.rs @@ -13,11 +13,15 @@ static EXTERNAL_HTTP_STD_REQUEST: Lazy = static EXTERNAL_CSS_REQUEST: Lazy = Lazy::new(|| Regex::new(r"^\.css(\?|$)").expect("Invalid regex")); -pub fn http_externals_rspack_plugin(css: bool) -> BoxPlugin { - ExternalsPlugin::new("module".to_owned(), vec![http_external_item(css)]).boxed() +pub fn http_externals_rspack_plugin(css: bool, web_async: bool) -> BoxPlugin { + if web_async { + ExternalsPlugin::new("import".to_owned(), vec![http_external_item_web_async(css)]).boxed() + } else { + ExternalsPlugin::new("module".to_owned(), vec![http_external_item_web(css)]).boxed() + } } -fn http_external_item(css: bool) -> ExternalItem { +fn http_external_item_web(css: bool) -> ExternalItem { ExternalItem::Fn(Box::new(move |ctx: ExternalItemFnCtx| { Box::pin(async move { if ctx.dependency_type == "url" { @@ -54,3 +58,41 @@ fn http_external_item(css: bool) -> ExternalItem { }) })) } + +fn http_external_item_web_async(css: bool) -> ExternalItem { + ExternalItem::Fn(Box::new(move |ctx: ExternalItemFnCtx| { + Box::pin(async move { + if ctx.dependency_type == "url" { + if EXTERNAL_HTTP_REQUEST.is_match(&ctx.request) { + return Ok(ExternalItemFnResult { + external_type: Some("asset".to_owned()), + result: Some(ExternalItemValue::String(ctx.request)), + }); + } + } else if css && ctx.dependency_type == "css-import" { + if EXTERNAL_HTTP_REQUEST.is_match(&ctx.request) { + return Ok(ExternalItemFnResult { + external_type: Some("css-import".to_owned()), + result: Some(ExternalItemValue::String(ctx.request)), + }); + } + } else if EXTERNAL_HTTP_STD_REQUEST.is_match(&ctx.request) { + if css && EXTERNAL_CSS_REQUEST.is_match(&ctx.request) { + return Ok(ExternalItemFnResult { + external_type: Some("css-import".to_owned()), + result: Some(ExternalItemValue::String(ctx.request)), + }); + } else { + return Ok(ExternalItemFnResult { + external_type: Some("import".to_owned()), + result: Some(ExternalItemValue::String(ctx.request)), + }); + } + } + Ok(ExternalItemFnResult { + external_type: None, + result: None, + }) + }) + })) +} diff --git a/crates/rspack_testing/src/test_config.rs b/crates/rspack_testing/src/test_config.rs index 5d589575783..775df548001 100644 --- a/crates/rspack_testing/src/test_config.rs +++ b/crates/rspack_testing/src/test_config.rs @@ -555,7 +555,9 @@ impl TestConfig { plugins.push(rspack_plugin_wasm::FetchCompileAsyncWasmPlugin {}.boxed()); plugins.push(rspack_plugin_wasm::AsyncWasmPlugin::new().boxed()); } - plugins.push(rspack_plugin_externals::http_externals_rspack_plugin(true)); + plugins.push(rspack_plugin_externals::http_externals_rspack_plugin( + true, false, + )); // Support resolving builtin loaders on the Native side plugins.push(crate::loader::BuiltinLoaderResolver.boxed()); diff --git a/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts b/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts index 3d4cbecd7c0..851b41b92b9 100644 --- a/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts +++ b/packages/rspack/src/builtin-plugin/HttpExternalsRspackPlugin.ts @@ -3,9 +3,10 @@ import { BuiltinPluginName, create } from "./base"; export const HttpExternalsRspackPlugin = create( BuiltinPluginName.HttpExternalsRspackPlugin, - (css: boolean): RawHttpExternalsRspackPluginOptions => { + (css: boolean, webAsync: boolean): RawHttpExternalsRspackPluginOptions => { return { - css + css, + webAsync }; } ); diff --git a/packages/rspack/src/config/zod.ts b/packages/rspack/src/config/zod.ts index f9a2ebb6348..a091ef83c82 100644 --- a/packages/rspack/src/config/zod.ts +++ b/packages/rspack/src/config/zod.ts @@ -681,6 +681,7 @@ export type Externals = z.infer; const externalsPresets = z.strictObject({ node: z.boolean().optional(), web: z.boolean().optional(), + webAsync: z.boolean().optional(), electron: z.boolean().optional(), electronMain: z.boolean().optional(), electronPreload: z.boolean().optional(), diff --git a/packages/rspack/src/rspackOptionsApply.ts b/packages/rspack/src/rspackOptionsApply.ts index afb4cb351b0..4ef8af8027e 100644 --- a/packages/rspack/src/rspackOptionsApply.ts +++ b/packages/rspack/src/rspackOptionsApply.ts @@ -72,9 +72,13 @@ export function optionsApply_compat( } if ( options.externalsPresets.web || + options.externalsPresets.webAsync || (options.externalsPresets.node && options.experiments.css) ) { - new HttpExternalsRspackPlugin(!!options.experiments.css).apply(compiler); + new HttpExternalsRspackPlugin( + !!options.experiments.css, + !!options.externalsPresets.webAsync + ).apply(compiler); } if (typeof options.output.chunkFormat === "string") { From 80d153f1c1cc2d746da09e8bbb0dabdd4c90979d Mon Sep 17 00:00:00 2001 From: Gengkun Date: Wed, 13 Sep 2023 13:51:52 +0800 Subject: [PATCH 16/49] fix: perf regression caused by optimizeTree hook (#4185) * fix: perf regression caused by optimizeTree hook * fix --- crates/node_binding/src/hook.rs | 4 ++-- crates/node_binding/src/plugins/mod.rs | 2 +- packages/rspack/src/Compiler.ts | 1 + 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/node_binding/src/hook.rs b/crates/node_binding/src/hook.rs index 84efc897e7d..38c56496b58 100644 --- a/crates/node_binding/src/hook.rs +++ b/crates/node_binding/src/hook.rs @@ -32,7 +32,7 @@ pub enum Hook { AfterCompile, FinishModules, OptimizeModules, - OptimizaTree, + OptimizeTree, /// webpack `compilation.hooks.chunkAsset` ChunkAsset, NormalModuleFactoryResolveForScheme, @@ -74,7 +74,7 @@ impl From for Hook { "afterCompile" => Hook::AfterCompile, "finishModules" => Hook::FinishModules, "optimizeModules" => Hook::OptimizeModules, - "optimizaTree" => Hook::OptimizaTree, + "optimizeTree" => Hook::OptimizeTree, "chunkAsset" => Hook::ChunkAsset, "normalModuleFactoryResolveForScheme" => Hook::NormalModuleFactoryResolveForScheme, "afterResolve" => Hook::AfterResolve, diff --git a/crates/node_binding/src/plugins/mod.rs b/crates/node_binding/src/plugins/mod.rs index b18d379ca31..619404e227f 100644 --- a/crates/node_binding/src/plugins/mod.rs +++ b/crates/node_binding/src/plugins/mod.rs @@ -539,7 +539,7 @@ impl rspack_core::Plugin for JsHooksAdapter { &self, _compilation: &mut rspack_core::Compilation, ) -> rspack_error::Result<()> { - if self.is_hook_disabled(&Hook::OptimizaTree) { + if self.is_hook_disabled(&Hook::OptimizeTree) { return Ok(()); } self diff --git a/packages/rspack/src/Compiler.ts b/packages/rspack/src/Compiler.ts index 87bd3ef8560..048783a7eb8 100644 --- a/packages/rspack/src/Compiler.ts +++ b/packages/rspack/src/Compiler.ts @@ -711,6 +711,7 @@ class Compiler { ), compilation: this.hooks.compilation, optimizeChunkModules: this.compilation.hooks.optimizeChunkModules, + optimizeTree: this.compilation.hooks.optimizeTree, finishModules: this.compilation.hooks.finishModules, optimizeModules: this.compilation.hooks.optimizeModules, chunkAsset: this.compilation.hooks.chunkAsset, From 7aa8e477551b510123f66ab83da6519109d6bab0 Mon Sep 17 00:00:00 2001 From: lipp <489435760@qq.com> Date: Wed, 13 Sep 2023 14:33:17 +0800 Subject: [PATCH 17/49] feat: add boolean type for builtins.html[0].inject (#3771) * feat: add boolean type for builtins.html[0].inject * refactor * fix * fix --------- Co-authored-by: ahabhgk --- crates/node_binding/binding.d.ts | 6 +- .../src/options/raw_builtins/raw_html.rs | 21 ++---- crates/rspack_plugin_html/src/config.rs | 16 +++-- crates/rspack_plugin_html/src/plugin.rs | 52 +++++++-------- .../rspack_plugin_html/src/visitors/asset.rs | 11 ++-- .../src/builtin-plugin/HtmlRspackPlugin.ts | 16 ++++- .../configCases/builtins/html-inject/index.js | 40 +++++++++++ .../builtins/html-inject/webpack.config.js | 45 +++++++++++++ pnpm-lock.yaml | 66 ++++++++----------- 9 files changed, 175 insertions(+), 98 deletions(-) create mode 100644 packages/rspack/tests/configCases/builtins/html-inject/index.js create mode 100644 packages/rspack/tests/configCases/builtins/html-inject/webpack.config.js diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index 7f4e7670c46..9c7c97f3c74 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -716,12 +716,12 @@ export interface RawHtmlRspackPluginOptions { template?: string templateContent?: string templateParameters?: Record - /** `head`, `body` or None */ - inject?: "head" | "body" + /** "head", "body" or "false" */ + inject: "head" | "body" | "false" /** path or `auto` */ publicPath?: string /** `blocking`, `defer`, or `module` */ - scriptLoading?: "blocking" | "defer" | "module" + scriptLoading: "blocking" | "defer" | "module" /** entry_chunk_name (only entry chunks are supported) */ chunks?: Array excludedChunks?: Array diff --git a/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs b/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs index 9c2d4319869..ac9ed5e4aec 100644 --- a/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs +++ b/crates/rspack_binding_options/src/options/raw_builtins/raw_html.rs @@ -25,14 +25,14 @@ pub struct RawHtmlRspackPluginOptions { pub template: Option, pub template_content: Option, pub template_parameters: Option>, - /// `head`, `body` or None - #[napi(ts_type = "\"head\" | \"body\"")] - pub inject: Option, + /// "head", "body" or "false" + #[napi(ts_type = "\"head\" | \"body\" | \"false\"")] + pub inject: RawHtmlInject, /// path or `auto` pub public_path: Option, /// `blocking`, `defer`, or `module` #[napi(ts_type = "\"blocking\" | \"defer\" | \"module\"")] - pub script_loading: Option, + pub script_loading: RawHtmlScriptLoading, /// entry_chunk_name (only entry chunks are supported) pub chunks: Option>, @@ -47,17 +47,10 @@ pub struct RawHtmlRspackPluginOptions { impl From for HtmlRspackPluginOptions { fn from(value: RawHtmlRspackPluginOptions) -> Self { - let inject = value - .inject - .as_ref() - .map(|s| HtmlInject::from_str(s).unwrap_or_else(|_| panic!("Invalid inject value: {s}"))); + let inject = HtmlInject::from_str(&value.inject).expect("Invalid inject value"); - let script_loading = HtmlScriptLoading::from_str( - &value - .script_loading - .unwrap_or_else(|| String::from("defer")), - ) - .expect("value.script_loading has unwrap_or_else so this will never happen"); + let script_loading = + HtmlScriptLoading::from_str(&value.script_loading).expect("Invalid script_loading value"); let sri = value.sri.as_ref().map(|s| { HtmlSriHashFunction::from_str(s).unwrap_or_else(|_| panic!("Invalid sri value: {s}")) diff --git a/crates/rspack_plugin_html/src/config.rs b/crates/rspack_plugin_html/src/config.rs index 1a0fcac121d..f5892bda760 100644 --- a/crates/rspack_plugin_html/src/config.rs +++ b/crates/rspack_plugin_html/src/config.rs @@ -14,6 +14,7 @@ use crate::sri::HtmlSriHashFunction; pub enum HtmlInject { Head, Body, + False, } impl FromStr for HtmlInject { @@ -24,9 +25,11 @@ impl FromStr for HtmlInject { Ok(HtmlInject::Head) } else if s.eq("body") { Ok(HtmlInject::Body) + } else if s.eq("false") { + Ok(HtmlInject::False) } else { Err(anyhow::Error::msg( - "inject in html config only support 'head' or 'body'", + "inject in html config only support 'head', 'body', or 'false'", )) } } @@ -70,8 +73,9 @@ pub struct HtmlRspackPluginOptions { pub template: Option, pub template_content: Option, pub template_parameters: Option>, - /// `head`, `body` or None - pub inject: Option, + /// `head`, `body`, `false` + #[serde(default = "default_inject")] + pub inject: HtmlInject, /// path or `auto` pub public_path: Option, /// `blocking`, `defer`, or `module` @@ -100,6 +104,10 @@ fn default_script_loading() -> HtmlScriptLoading { HtmlScriptLoading::Defer } +fn default_inject() -> HtmlInject { + HtmlInject::Head +} + impl Default for HtmlRspackPluginOptions { fn default() -> HtmlRspackPluginOptions { HtmlRspackPluginOptions { @@ -107,7 +115,7 @@ impl Default for HtmlRspackPluginOptions { template: None, template_content: None, template_parameters: None, - inject: None, + inject: default_inject(), public_path: None, script_loading: default_script_loading(), chunks: None, diff --git a/crates/rspack_plugin_html/src/plugin.rs b/crates/rspack_plugin_html/src/plugin.rs index d6868a6c5e4..17b3ad12724 100644 --- a/crates/rspack_plugin_html/src/plugin.rs +++ b/crates/rspack_plugin_html/src/plugin.rs @@ -132,36 +132,28 @@ impl Plugin for HtmlRspackPlugin { .collect::>(); let mut tags = vec![]; - for (asset_name, asset) in included_assets { - if let Some(extension) = Path::new(&asset_name).extension() { - let asset_uri = format!( - "{}{asset_name}", - config.get_public_path(compilation, &self.config.filename), - ); - let mut tag: Option = None; - if extension.eq_ignore_ascii_case("css") { - tag = Some(HTMLPluginTag::create_style( - &asset_uri, - Some(if let Some(inject) = &config.inject { - *inject - } else { - HtmlInject::Head - }), - )); - } else if extension.eq_ignore_ascii_case("js") || extension.eq_ignore_ascii_case("mjs") { - tag = Some(HTMLPluginTag::create_script( - &asset_uri, - Some(if let Some(inject) = &config.inject { - *inject - } else { - HtmlInject::Head - }), - &config.script_loading, - )) - } - - if let Some(tag) = tag { - tags.push((tag, asset)); + // if inject is 'false', don't do anything + if !matches!(config.inject, HtmlInject::False) { + for (asset_name, asset) in included_assets { + if let Some(extension) = Path::new(&asset_name).extension() { + let asset_uri = format!( + "{}{asset_name}", + config.get_public_path(compilation, &self.config.filename), + ); + let mut tag: Option = None; + if extension.eq_ignore_ascii_case("css") { + tag = Some(HTMLPluginTag::create_style(&asset_uri, config.inject)); + } else if extension.eq_ignore_ascii_case("js") || extension.eq_ignore_ascii_case("mjs") { + tag = Some(HTMLPluginTag::create_script( + &asset_uri, + config.inject, + &config.script_loading, + )) + } + + if let Some(tag) = tag { + tags.push((tag, asset)); + } } } } diff --git a/crates/rspack_plugin_html/src/visitors/asset.rs b/crates/rspack_plugin_html/src/visitors/asset.rs index 0cd90fe5169..7e00a6cfa9d 100644 --- a/crates/rspack_plugin_html/src/visitors/asset.rs +++ b/crates/rspack_plugin_html/src/visitors/asset.rs @@ -17,15 +17,15 @@ pub struct HTMLPluginTag { pub tag_name: String, pub attributes: Vec, pub void_tag: bool, - // `head` or `body` + // `head`, `body`, `false` pub append_to: HtmlInject, } impl HTMLPluginTag { - pub fn create_style(href: &str, append_to: Option) -> HTMLPluginTag { + pub fn create_style(href: &str, append_to: HtmlInject) -> HTMLPluginTag { HTMLPluginTag { tag_name: "link".to_string(), - append_to: append_to.unwrap_or(HtmlInject::Head), + append_to, attributes: vec![ HtmlPluginAttribute { attr_name: "href".to_string(), @@ -42,7 +42,7 @@ impl HTMLPluginTag { pub fn create_script( src: &str, - append_to: Option, + append_to: HtmlInject, script_loading: &HtmlScriptLoading, ) -> HTMLPluginTag { let mut attributes = vec![HtmlPluginAttribute { @@ -67,7 +67,7 @@ impl HTMLPluginTag { HTMLPluginTag { tag_name: "script".to_string(), - append_to: append_to.unwrap_or(HtmlInject::Body), + append_to, attributes, void_tag: false, } @@ -107,6 +107,7 @@ impl<'a, 'c> AssetWriter<'a, 'c> { HtmlInject::Body => { body_tags.push(ele); } + _ => (), } } AssetWriter { diff --git a/packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts b/packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts index 4a8bf1f9543..3fb22b67473 100644 --- a/packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts +++ b/packages/rspack/src/builtin-plugin/HtmlRspackPlugin.ts @@ -8,7 +8,7 @@ const htmlRspackPluginOptions = z.strictObject({ template: z.string().optional(), templateContent: z.string().optional(), templateParameters: z.record(z.string()).optional(), - inject: z.enum(["head", "body"]).optional(), + inject: z.enum(["head", "body"]).or(z.boolean()).optional(), publicPath: z.string().optional(), scriptLoading: z.enum(["blocking", "defer", "module"]).optional(), chunks: z.string().array().optional(), @@ -34,9 +34,21 @@ export const HtmlRspackPlugin = create( }; } } + const scriptLoading = c.scriptLoading ?? "defer"; + const configInject = c.inject ?? true; + const inject = + configInject === true + ? scriptLoading === "blocking" + ? "body" + : "head" + : configInject === false + ? "false" + : configInject; return { ...c, - meta + meta, + scriptLoading, + inject }; } ); diff --git a/packages/rspack/tests/configCases/builtins/html-inject/index.js b/packages/rspack/tests/configCases/builtins/html-inject/index.js new file mode 100644 index 00000000000..1d427ecf57e --- /dev/null +++ b/packages/rspack/tests/configCases/builtins/html-inject/index.js @@ -0,0 +1,40 @@ +const fs = require("fs"); +const path = require("path"); + +it("body-index.html inject", () => { + const htmlPath = path.join(__dirname, "./body-index.html"); + const htmlContent = fs.readFileSync(htmlPath, "utf-8"); + expect( + htmlContent.includes('') + ).toBe(true); +}); + +it("head-index.html inject", () => { + const htmlPath = path.join(__dirname, "./head-index.html"); + const htmlContent = fs.readFileSync(htmlPath, "utf-8"); + expect( + htmlContent.includes('') + ).toBe(true); +}); + +it("true-blocking-index.html inject", () => { + const htmlPath = path.join(__dirname, "./true-blocking-index.html"); + const htmlContent = fs.readFileSync(htmlPath, "utf-8"); + expect(htmlContent.includes('')).toBe( + true + ); +}); + +it("true-defer-index.html inject", () => { + const htmlPath = path.join(__dirname, "./true-defer-index.html"); + const htmlContent = fs.readFileSync(htmlPath, "utf-8"); + expect( + htmlContent.includes('') + ).toBe(true); +}); + +it("false-index.html inject", () => { + const htmlPath = path.join(__dirname, "./false-index.html"); + const htmlContent = fs.readFileSync(htmlPath, "utf-8"); + expect(htmlContent.includes('