From dc39714e0ad170fc6de71a1535342ffe36ae1990 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=88=B4=E9=99=88=E5=A8=81?= Date: Wed, 14 Jan 2026 20:21:52 +0800 Subject: [PATCH] refactor!: drop CommonJS build and drop support for Node 18 --- .github/workflows/reusable-build-test.yml | 4 +- package.json | 2 +- packages/create-rspack/rslib.config.ts | 2 +- packages/create-rspack/tsconfig.json | 1 - packages/rspack-browser/package.json | 5 +- packages/rspack-cli/bin/rspack.js | 4 +- packages/rspack-cli/package.json | 5 +- packages/rspack-cli/rslib.config.mts | 13 +- packages/rspack-cli/rstest.config.ts | 2 +- packages/rspack-cli/src/utils/crossImport.ts | 3 + packages/rspack-cli/src/utils/loadConfig.ts | 3 + packages/rspack-cli/src/utils/rspackCore.ts | 13 +- ...js-api-cjs.test.ts => js-api-cjs.test.cts} | 15 +- ...js-api-esm.test.mts => js-api-esm.test.ts} | 7 +- packages/rspack-cli/tests/package.json | 3 + packages/rspack-cli/tsconfig.json | 4 +- .../src/helper/expect/placeholder.ts | 4 + packages/rspack/etc/core.api.md | 389 +++++++++++++++++- packages/rspack/hot/dev-server.js | 21 +- packages/rspack/hot/emitter.js | 2 +- packages/rspack/hot/lazy-compilation-node.js | 12 +- packages/rspack/hot/lazy-compilation-web.js | 5 +- packages/rspack/hot/log-apply-result.js | 11 +- packages/rspack/hot/log.js | 22 +- packages/rspack/hot/only-dev-server.js | 23 +- packages/rspack/hot/poll.js | 19 +- packages/rspack/hot/signal.js | 22 +- packages/rspack/move-tinypool.js | 9 +- packages/rspack/package.json | 6 +- ...ser.config.mts => rslib.browser.config.ts} | 76 ++-- .../{rslib.config.mts => rslib.config.ts} | 116 ++++-- packages/rspack/src/Compiler.ts | 5 +- packages/rspack/src/ExecuteModulePlugin.ts | 3 + .../src/builtin-plugin/EsmLibraryPlugin.ts | 4 +- .../src/builtin-plugin/HttpUriPlugin.ts | 4 + .../SubresourceIntegrityPlugin.ts | 3 + .../src/builtin-plugin/css-extract/index.ts | 2 +- .../src/builtin-plugin/css-extract/loader.ts | 2 +- .../src/builtin-plugin/html-plugin/plugin.ts | 4 +- .../lazy-compilation/lazyCompilation.ts | 2 +- .../lazy-compilation/middleware.ts | 3 + packages/rspack/src/config/target.ts | 3 + .../src/container/ModuleFederationPlugin.ts | 5 +- packages/rspack/src/exports.ts | 2 +- packages/rspack/src/index.ts | 2 +- .../rspack/src/loader-runner/loadLoader.ts | 3 + packages/rspack/src/loader-runner/service.ts | 5 +- packages/rspack/src/loader-runner/worker.ts | 12 +- .../rspack/src/node/NodeWatchFileSystem.ts | 3 + .../runtime/moduleFederationDefaultRuntime.js | 4 +- packages/rspack/src/util/createHash.ts | 3 + packages/rspack/tsconfig.browser.json | 2 + packages/rspack/tsconfig.json | 2 + pnpm-lock.yaml | 17 +- tests/e2e/cases/chunk/esm_split/src/index.js | 2 +- .../e2e/cases/chunk/issue-4936/index.test.ts | 2 +- tests/e2e/cases/chunk/issue-4936/src/index.js | 2 +- .../css/chunk-loading-order/src/index.js | 2 +- .../css/import-empty-css-file/src/index.js | 2 +- .../file/context-delete-file/src/index.js | 6 +- .../cases/file/missing-files/index.test.ts | 6 +- .../e2e/cases/file/missing-files/src/index.js | 4 +- .../cases/hooks/asset-emitted/src/index.js | 2 +- .../remove-optimized-module/comp/index.js | 2 +- .../remove-optimized-module/index.js | 2 +- .../remove-optimized-module/index.test.ts | 2 +- .../remove-optimized-module/package.json | 1 + .../module-federation/runtime-plugin.js | 4 +- .../persistent-cache/src/index.js | 2 +- .../{loader.js => loader.cjs} | 0 .../rspack.config.js | 2 +- .../loader.js | 11 +- .../make/rewrite-factorize-request/index.js | 2 +- .../{loader.js => loader.cjs} | 0 .../rspack.config.js | 4 +- .../persistent-cache/rename-file/index.js | 4 +- .../e2e/cases/worker/worker-hmr/src/worker.js | 2 +- tests/e2e/fixtures/pathInfo.ts | 5 +- tests/e2e/fixtures/rspack.ts | 3 + tests/e2e/package.json | 4 +- tests/e2e/tsconfig.json | 2 + tests/rspack-test/errorCases/error-read.js | 2 +- tests/rspack-test/errorCases/error-write.js | 14 +- .../rspack-test/errorCases/warning-modify.js | 12 +- .../css/recovery/__snapshots__/web/2.snap.txt | 101 +++-- .../multiCompilerCases/pressure.js | 2 +- tests/rspack-test/package.json | 2 +- .../logging/__snapshots__/stats.txt | 12 +- website/docs/en/guide/start/quick-start.mdx | 1 + website/docs/zh/guide/start/quick-start.mdx | 1 + 90 files changed, 846 insertions(+), 299 deletions(-) rename packages/rspack-cli/tests/api/type/{js-api-cjs.test.ts => js-api-cjs.test.cts} (66%) rename packages/rspack-cli/tests/api/type/{js-api-esm.test.mts => js-api-esm.test.ts} (86%) create mode 100644 packages/rspack-cli/tests/package.json rename packages/rspack/{rslib.browser.config.mts => rslib.browser.config.ts} (80%) rename packages/rspack/{rslib.config.mts => rslib.config.ts} (54%) rename tests/e2e/cases/make/failed_module_by_js_loader/{loader.js => loader.cjs} (100%) rename tests/e2e/cases/make/rewrite-factorize-request/{loader.js => loader.cjs} (100%) diff --git a/.github/workflows/reusable-build-test.yml b/.github/workflows/reusable-build-test.yml index 653b70db4e73..dce32305a212 100644 --- a/.github/workflows/reusable-build-test.yml +++ b/.github/workflows/reusable-build-test.yml @@ -71,7 +71,7 @@ jobs: matrix: node: ${{ fromJSON( inputs.target == 'wasm32-wasip1-threads'&& '[24]' - || contains(inputs.target, 'linux') && '[18, 20, 22]' + || contains(inputs.target, 'linux') && '[20, 22, 24]' || '[22]') }} name: Test Node ${{ matrix.node }} defaults: @@ -105,7 +105,7 @@ jobs: - name: Pnpm Install uses: ./.github/actions/pnpm/install-dependencies with: - save-if: ${{ github.ref_name == 'main' && matrix.node == '18' }} + save-if: ${{ github.ref_name == 'main' && matrix.node == '20' }} ### x86_64-unknown-linux-gnu - name: Test x86_64-unknown-linux-gnu diff --git a/package.json b/package.json index bb382484ad95..8132001260ce 100644 --- a/package.json +++ b/package.json @@ -74,7 +74,7 @@ "cross-env": "^10.1.0", "husky": "^9.1.7", "is-ci": "4.1.0", - "@rstest/core": "^0.7.8", + "@rstest/core": "^0.7.9", "lint-staged": "^16.2.7", "prettier": "3.7.4", "prettier-2": "npm:prettier@2.8.8", diff --git a/packages/create-rspack/rslib.config.ts b/packages/create-rspack/rslib.config.ts index fc41566e1322..18ef355c8013 100644 --- a/packages/create-rspack/rslib.config.ts +++ b/packages/create-rspack/rslib.config.ts @@ -1,5 +1,5 @@ import { defineConfig } from '@rslib/core'; export default defineConfig({ - lib: [{ format: 'esm', syntax: ['node 18.12'] }], + lib: [{ format: 'esm', syntax: ['es2023'] }], }); diff --git a/packages/create-rspack/tsconfig.json b/packages/create-rspack/tsconfig.json index 9fba7aae090a..370cb6c855fd 100644 --- a/packages/create-rspack/tsconfig.json +++ b/packages/create-rspack/tsconfig.json @@ -2,7 +2,6 @@ "extends": "../../tsconfig.base.json", "include": ["src"], "compilerOptions": { - "module": "NodeNext", "outDir": "dist", "rootDir": "src" } diff --git a/packages/rspack-browser/package.json b/packages/rspack-browser/package.json index c6c5abcdf943..8bfe544775b2 100644 --- a/packages/rspack-browser/package.json +++ b/packages/rspack-browser/package.json @@ -5,7 +5,6 @@ "license": "MIT", "description": "Rspack for running in the browser. This is still in early stage and may not follow the semver.", "type": "module", - "main": "./dist/index.mjs", "types": "./dist/browser/index.d.ts", "publishConfig": { "access": "public", @@ -14,9 +13,9 @@ "exports": { ".": { "types": "./dist/browser/index.d.ts", - "default": "./dist/index.mjs" + "default": "./dist/index.js" }, - "./wasi-worker-browser.mjs": "./wasi-worker-browser.mjs", + "./wasi-worker-browser.js": "./wasi-worker-browser.js", "./package.json": "./package.json" }, "scripts": { diff --git a/packages/rspack-cli/bin/rspack.js b/packages/rspack-cli/bin/rspack.js index 1efac6f95317..4e6b5da5c907 100755 --- a/packages/rspack-cli/bin/rspack.js +++ b/packages/rspack-cli/bin/rspack.js @@ -1,5 +1,5 @@ #!/usr/bin/env node -const nodeModule = require('node:module'); +import nodeModule from 'node:module'; // enable on-disk code caching of all modules loaded by Node.js // requires Nodejs >= 22.8.0 @@ -15,7 +15,7 @@ if (enableCompileCache) { // make it easier to identify the process via activity monitor or other tools process.title = 'rspack-node'; -const { RspackCLI } = require('../dist/index'); +import { RspackCLI } from '../dist/index.js'; async function runCLI() { const cli = new RspackCLI(); diff --git a/packages/rspack-cli/package.json b/packages/rspack-cli/package.json index f9b9bdc006b5..b1bf78796671 100644 --- a/packages/rspack-cli/package.json +++ b/packages/rspack-cli/package.json @@ -10,15 +10,14 @@ "directory": "packages/rspack-cli" }, "license": "MIT", + "type": "module", "exports": { ".": { "types": "./dist/index.d.ts", - "import": "./dist/index.mjs", - "require": "./dist/index.js" + "default": "./dist/index.js" }, "./package.json": "./package.json" }, - "main": "./dist/index.js", "types": "./dist/index.d.ts", "bin": { "rspack": "./bin/rspack.js" diff --git a/packages/rspack-cli/rslib.config.mts b/packages/rspack-cli/rslib.config.mts index 53dd1cdb62c8..07c2abf99ac9 100644 --- a/packages/rspack-cli/rslib.config.mts +++ b/packages/rspack-cli/rslib.config.mts @@ -1,17 +1,18 @@ -import { createRequire } from 'node:module'; import { defineConfig } from '@rslib/core'; - -const require = createRequire(import.meta.url); +import packageJson from './package.json' with { type: 'json' }; export default defineConfig({ lib: [ - { format: 'cjs', syntax: ['node 18.12'], dts: { bundle: false } }, - { format: 'esm', syntax: ['node 18.12'] }, + { + format: 'esm', + syntax: ['es2023'], + dts: true, + }, ], source: { tsconfigPath: './tsconfig.build.json', define: { - RSPACK_CLI_VERSION: JSON.stringify(require('./package.json').version), + RSPACK_CLI_VERSION: JSON.stringify(packageJson.version), }, }, }); diff --git a/packages/rspack-cli/rstest.config.ts b/packages/rspack-cli/rstest.config.ts index 17b6894cc8d6..a290461560d7 100644 --- a/packages/rspack-cli/rstest.config.ts +++ b/packages/rspack-cli/rstest.config.ts @@ -16,7 +16,7 @@ export default defineConfig({ testEnvironment: 'node', globals: true, testTimeout: process.env.CI ? 200000 : 30000, - include: ['tests/**/*.test.ts', 'tests/**/*.test.js'], + include: ['tests/**/*.test.{ts,js,cts}'], source: { tsconfigPath: 'tests/tsconfig.json', }, diff --git a/packages/rspack-cli/src/utils/crossImport.ts b/packages/rspack-cli/src/utils/crossImport.ts index 272088cf6990..a9ee358b0465 100644 --- a/packages/rspack-cli/src/utils/crossImport.ts +++ b/packages/rspack-cli/src/utils/crossImport.ts @@ -1,6 +1,9 @@ +import { createRequire } from 'node:module'; import { pathToFileURL } from 'node:url'; import { isEsmFile } from './isEsmFile'; +const require = createRequire(import.meta.url); + export const crossImport = async (path: string): Promise => { if (isEsmFile(path)) { const url = pathToFileURL(path).href; diff --git a/packages/rspack-cli/src/utils/loadConfig.ts b/packages/rspack-cli/src/utils/loadConfig.ts index 1457f4009ce6..c14b598abc08 100644 --- a/packages/rspack-cli/src/utils/loadConfig.ts +++ b/packages/rspack-cli/src/utils/loadConfig.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import type { MultiRspackOptions, RspackOptions } from '@rspack/core'; import { addHook } from 'pirates'; @@ -9,6 +10,8 @@ import isTsFile, { TS_EXTENSION } from './isTsFile'; import type { CommonOptions } from './options'; import { rspack } from './rspackCore'; +const require = createRequire(import.meta.url); + const injectInlineSourceMap = ({ code, map, diff --git a/packages/rspack-cli/src/utils/rspackCore.ts b/packages/rspack-cli/src/utils/rspackCore.ts index 33dbaa7e95a8..5b00538c0d27 100644 --- a/packages/rspack-cli/src/utils/rspackCore.ts +++ b/packages/rspack-cli/src/utils/rspackCore.ts @@ -1,12 +1 @@ -import { createRequire } from 'node:module'; - -/** - * Currently, Rspack only provides a CJS bundle, so we use require to load it - * for better startup performance. - * https://github.com/nodejs/node/issues/59913 - */ -// @ts-expect-error can be removed after add `type: "module"` to package.json -const require = createRequire(import.meta.url); -const rspack: (typeof import('@rspack/core'))['rspack'] = require('@rspack/core'); - -export { rspack }; +export { rspack } from '@rspack/core'; diff --git a/packages/rspack-cli/tests/api/type/js-api-cjs.test.ts b/packages/rspack-cli/tests/api/type/js-api-cjs.test.cts similarity index 66% rename from packages/rspack-cli/tests/api/type/js-api-cjs.test.ts rename to packages/rspack-cli/tests/api/type/js-api-cjs.test.cts index 91ebe0a1d746..d7d0ee6f507f 100644 --- a/packages/rspack-cli/tests/api/type/js-api-cjs.test.ts +++ b/packages/rspack-cli/tests/api/type/js-api-cjs.test.cts @@ -5,21 +5,24 @@ import assert from 'node:assert'; type IsFunction = T extends (...args: any[]) => any ? true : false; +// not real Node.js behavior // https://github.com/web-infra-dev/rspack/issues/8095 describe.concurrent( 'js-api-type should be correct when requiring from @rspack/core', () => { it('cjs default require', async () => { + // const rspack = require('@rspack/core') type Truthy = IsFunction; const truthy: Truthy = true; truthy; assert(rspackCjsDefaultRequire.BannerPlugin); - assert(typeof rspackCjsDefaultRequire === 'function'); - const compiler = rspackCjsDefaultRequire({}); + assert(typeof rspackCjsDefaultRequire === 'object'); + const compiler = rspackCjsDefaultRequire.default({}); assert(compiler); }); it('cjs named require', async () => { + // const { rspack } = require('@rspack/core') type Truthy = IsFunction; const truthy: Truthy = true; truthy; @@ -29,9 +32,13 @@ describe.concurrent( assert(compiler); }); - it('rspack.default should not exist in cjs require', async () => { + it('rspack.default', async () => { + // const { rspack } = require('@rspack/core') + // rspack.default should be undefined assert(!(rspackCjsNamedRequire as any).default); - assert(!(rspackCjsDefaultRequire as any).default); + // const rspack = require('@rspack/core') + // rspack.default should be defined + assert(!!(rspackCjsDefaultRequire as any).default); }); }, ); diff --git a/packages/rspack-cli/tests/api/type/js-api-esm.test.mts b/packages/rspack-cli/tests/api/type/js-api-esm.test.ts similarity index 86% rename from packages/rspack-cli/tests/api/type/js-api-esm.test.mts rename to packages/rspack-cli/tests/api/type/js-api-esm.test.ts index 34651d84d6ee..5ff5b2577287 100644 --- a/packages/rspack-cli/tests/api/type/js-api-esm.test.mts +++ b/packages/rspack-cli/tests/api/type/js-api-esm.test.ts @@ -5,15 +5,14 @@ import rspackEsmDefaultImport, { type IsFunction = T extends (...args: any[]) => any ? true : false; +// not real Node.js behavior // https://github.com/web-infra-dev/rspack/issues/8095 describe.concurrent( 'js-api-type should be correct when importing from @rspack/core', () => { it('esm default import', async () => { - // rspack has no default export now - type Falsy = IsFunction; - const falsy: Falsy = false; - falsy; + assert(rspackEsmDefaultImport); + assert(typeof rspackEsmDefaultImport === 'function'); assert(rspackEsmDefaultImport.BannerPlugin); }); diff --git a/packages/rspack-cli/tests/package.json b/packages/rspack-cli/tests/package.json new file mode 100644 index 000000000000..5bbefffbabee --- /dev/null +++ b/packages/rspack-cli/tests/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/packages/rspack-cli/tsconfig.json b/packages/rspack-cli/tsconfig.json index b8a128f07d3b..518c4b7c1620 100644 --- a/packages/rspack-cli/tsconfig.json +++ b/packages/rspack-cli/tsconfig.json @@ -3,7 +3,9 @@ "include": ["src"], "compilerOptions": { "outDir": "dist", - "rootDir": "src" + "rootDir": "src", + "module": "ES2022", + "moduleResolution": "bundler" }, "references": [ { diff --git a/packages/rspack-test-tools/src/helper/expect/placeholder.ts b/packages/rspack-test-tools/src/helper/expect/placeholder.ts index 1a4a7d9484f6..248ca887c8e2 100644 --- a/packages/rspack-test-tools/src/helper/expect/placeholder.ts +++ b/packages/rspack-test-tools/src/helper/expect/placeholder.ts @@ -21,6 +21,10 @@ const placeholderSerializer = createSnapshotSerializer({ match: __RSPACK_PATH__, mark: 'rspack_root', }, + { + match: /\/packages\/rspack/g, + mark: 'rspack_root', + }, { match: /:\d+:\d+-\d+:\d+/g, mark: 'line_col_range', diff --git a/packages/rspack/etc/core.api.md b/packages/rspack/etc/core.api.md index 66105177cde2..1b71f52bf006 100644 --- a/packages/rspack/etc/core.api.md +++ b/packages/rspack/etc/core.api.md @@ -84,7 +84,6 @@ import { Server as Server_3 } from 'http'; import { ServerOptions as ServerOptions_2 } from 'https'; import { ServerResponse } from 'http'; import { SourceMapDevToolPluginOptions } from '@rspack/binding'; -import sources = require('../compiled/webpack-sources'); import { StatSyncFn } from 'fs'; import type * as stream from 'node:stream'; import { sync } from '@rspack/binding'; @@ -516,11 +515,36 @@ interface BreakStatement extends Node_4, HasSpan { // @public (undocumented) type BufferCallback = (err: NodeJS.ErrnoException | null, data?: Buffer) => void; +// @public (undocumented) +interface BufferedMap { + file: string; + + mappings?: Buffer_2; + + names: string[]; + + sourceRoot?: string; + + sources: string[]; + + sourcesContent?: ("" | Buffer_2)[]; + + version: number; +} + // @public (undocumented) type BufferEncodingOption = 'buffer' | { encoding: 'buffer'; }; +// @public (undocumented) +interface BufferEntry { + // (undocumented) + bufferedMap?: null | BufferedMap; + // (undocumented) + map?: null | RawSourceMap_2; +} + // @public export type BundlerInfoOptions = { version?: string; @@ -564,6 +588,49 @@ class Cache_2 { storeBuildDependencies(dependencies: Iterable, callback: CallbackCache): void; } +// @public (undocumented) +interface CachedData { + buffer: Buffer_2; + + hash?: (string | Buffer_2)[]; + + maps: Map; + + size?: number; + + source?: boolean; +} + +// @public (undocumented) +class CachedSource extends Source { + constructor(source: Source | (() => Source), cachedData?: CachedData); + // (undocumented) + getCachedData(): CachedData; + // (undocumented) + original(): Source; + // (undocumented) + originalLazy(): Source | (() => Source); + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + // @public (undocumented) class CacheFacade { constructor(cache: Cache_2, name: string, hashFunction: string | HashConstructor); @@ -881,6 +948,13 @@ interface CommonJsConfig extends BaseModuleConfig { type: "commonjs"; } +// @public (undocumented) +class CompatSource extends Source { + constructor(sourceLike: SourceLike); + // (undocumented) + static from(sourceLike: SourceLike): Source; +} + // @public (undocumented) export class Compilation { // (undocumented) @@ -1330,6 +1404,39 @@ interface ComputedPropName extends Node_4, HasSpan { export { ConcatenatedModule } +// @public (undocumented) +class ConcatSource extends Source { + constructor(...args: ConcatSourceChild[]); + // (undocumented) + add(item: ConcatSourceChild): void; + // (undocumented) + addAllSkipOptimizing(items: ConcatSourceChild[]): void; + // (undocumented) + getChildren(): Source[]; + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + +// @public (undocumented) +type ConcatSourceChild = string | Source | SourceLike; + // @public (undocumented) interface ConditionalExpression extends ExpressionBase { // (undocumented) @@ -2855,6 +2962,15 @@ interface FunctionExpression extends Fn, ExpressionBase { type: "FunctionExpression"; } +// @public (undocumented) +interface GeneratedSourceInfo { + generatedColumn?: number; + + generatedLine?: number; + + source?: string; +} + // @public export type GeneratorOptionsByModuleType = GeneratorOptionsByModuleTypeKnown | GeneratorOptionsByModuleTypeUnknown; @@ -5337,12 +5453,26 @@ interface ObjectPattern extends PatternBase { // @public (undocumented) type ObjectPatternProperty = KeyValuePatternProperty | AssignmentPatternProperty | RestElement; +// @public (undocumented) +type OnChunk = ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void; + // @public (undocumented) type OnCloseCallback = (proxyRes: Response_2, proxySocket: net.Socket, proxyHead: any) => void; // @public (undocumented) type OnErrorCallback = (err: Error, req: Request_2, res: Response_2, target?: string | Partial) => void; +// @public (undocumented) +type OnName = (nameIndex: number, name: string) => void; + // @public (undocumented) type OnOpenCallback = (proxySocket: net.Socket) => void; @@ -5355,6 +5485,13 @@ type OnProxyReqWsCallback = (proxyReq: http.ClientRequest, req: Request_2, socke // @public (undocumented) type OnProxyResCallback = (proxyRes: http.IncomingMessage, req: Request_2, res: Response_2) => void; +// @public (undocumented) +type OnSource = ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void; + // @public (undocumented) type Open = (file: PathLike, flags: undefined | string | number, callback: (arg0: null | NodeJS.ErrnoException, arg1?: number) => void) => void; @@ -5520,6 +5657,32 @@ interface Options extends Config_2 { swcrcRoots?: boolean | MatchPattern | MatchPattern[]; } +// @public (undocumented) +class OriginalSource extends Source { + constructor(value: string | Buffer_2, name: string); + // (undocumented) + getName(): string; + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + _onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + // @public const OriginEntryPlugin: { new (context: string, entry: string, options?: string | EntryOptions | undefined): { @@ -5856,6 +6019,34 @@ export type Plugins = Plugin_2[]; // @public (undocumented) type Port = number | LiteralUnion<'auto', string>; +// @public (undocumented) +class PrefixSource extends Source { + constructor(prefix: string, source: string | Source | Buffer_2); + // (undocumented) + getPrefix(): string; + // (undocumented) + original(): Source; + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + // @public (undocumented) type PrintedElement = { element: string; @@ -6012,6 +6203,32 @@ export type PublicPath = LiteralUnion<'auto', string> | Exclude) => void; +// @public (undocumented) +class RawSource extends Source { + constructor(value: string | Buffer_2, convertToString?: boolean); + // (undocumented) + isBuffer(): boolean; + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + // @public (undocumented) export interface RawSourceMap { debugId?: string; @@ -6262,6 +6479,57 @@ const RemoveDuplicateModulesPlugin: { }; }; +// @public (undocumented) +class Replacement { + constructor(start: number, end: number, content: string, name?: string); + // (undocumented) + content: string; + // (undocumented) + end: number; + // (undocumented) + index?: number; + // (undocumented) + name?: string; + // (undocumented) + start: number; +} + +// @public (undocumented) +class ReplaceSource extends Source { + constructor(source: Source, name?: string); + // (undocumented) + getName(): undefined | string; + // (undocumented) + getReplacements(): Replacement[]; + // (undocumented) + insert(pos: number, newValue: string, name?: string): void; + // (undocumented) + original(): Source; + // (undocumented) + replace(start: number, end: number, newValue: string, name?: string): void; + // (undocumented) + static Replacement: typeof Replacement; + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + // @public (undocumented) type Request_2 = IncomingMessage_2; @@ -6485,6 +6753,7 @@ type Rspack = typeof rspack_2 & typeof rspackExports & { const rspack: Rspack; export default rspack; export { rspack } +export { rspack as webpack } // @public (undocumented) function rspack_2(options: MultiRspackOptions): MultiCompiler; @@ -7360,6 +7629,11 @@ export const sharing: { SharePlugin: typeof SharePlugin; }; +// @public (undocumented) +class SizeOnlySource extends Source { + constructor(size: number); +} + // @public (undocumented) export type SnapshotOptions = {}; @@ -7387,6 +7661,21 @@ interface SourceAndMap { source: SourceValue; } +// @public (undocumented) +interface SourceLike { + buffer?: () => Buffer_2; + + map?: (options?: MapOptions) => null | RawSourceMap_2; + + size?: () => number; + + source: () => SourceValue; + + sourceAndMap?: (options?: MapOptions) => SourceAndMap; + + updateHash?: (hash: HashLike) => void; +} + // @public (undocumented) export const SourceMapDevToolPlugin: { new (options: SourceMapDevToolPluginOptions): { @@ -7403,6 +7692,75 @@ export { SourceMapDevToolPluginOptions } // @public export type SourceMapFilename = string; +// @public (undocumented) +class SourceMapSource extends Source { + constructor( + value: string | Buffer_2, + name: string, + sourceMap?: string | RawSourceMap_2 | Buffer_2, + originalSource?: string | Buffer_2, + innerSourceMap?: string | RawSourceMap_2 | Buffer_2, + removeOriginalSource?: boolean, + ); + // (undocumented) + getArgsAsBuffers(): [ + Buffer_2, + string, + Buffer_2, + undefined | Buffer_2, + undefined | Buffer_2, + undefined | boolean, + ]; + // (undocumented) + streamChunks( + options: StreamChunksOptions, + onChunk: ( + chunk: undefined | string, + generatedLine: number, + generatedColumn: number, + sourceIndex: number, + originalLine: number, + originalColumn: number, + nameIndex: number, + ) => void, + onSource: ( + sourceIndex: number, + source: null | string, + sourceContent?: string, + ) => void, + onName: (nameIndex: number, name: string) => void, + ): GeneratedSourceInfo; +} + +declare namespace sources { + export { + util_2 as util, + OnChunk, + OnName, + OnSource, + Source, + RawSource, + OriginalSource, + SourceMapSource, + CachedSource, + ConcatSource, + ReplaceSource, + PrefixSource, + SizeOnlySource, + CompatSource, + CachedData, + SourceLike, + ConcatSourceChild, + Replacement, + HashLike, + MapOptions, + RawSourceMap_2 as RawSourceMap, + SourceAndMap, + SourceValue, + GeneratedSourceInfo, + StreamChunksOptions + } +} export { sources } // @public (undocumented) @@ -7733,6 +8091,16 @@ type StatSyncOptions = { throwIfNoEntry?: boolean; }; +// @public (undocumented) +interface StreamChunksOptions { + // (undocumented) + columns?: boolean; + // (undocumented) + finalSource?: boolean; + // (undocumented) + source?: boolean; +} + // @public (undocumented) interface StreamOptions { // (undocumented) @@ -9081,6 +9449,25 @@ export const util: { cleverMerge: (first: First, second: Second) => First | Second | (First & Second); }; +// @public (undocumented) +namespace util_2 { + // (undocumented) + namespace stringBufferUtils { + let // (undocumented) + disableDualStringBufferCaching: () => void; + let // (undocumented) + enableDualStringBufferCaching: () => void; + let // (undocumented) + internString: (str: string) => string; + let // (undocumented) + isDualStringBufferCachingEnabled: () => boolean; + let // (undocumented) + enterStringInterningRange: () => void; + let // (undocumented) + exitStringInterningRange: () => void; + } + } + // @public (undocumented) export class ValidationError extends Error { constructor(message: string); diff --git a/packages/rspack/hot/dev-server.js b/packages/rspack/hot/dev-server.js index 63808e2d48e7..25f9682ba1df 100644 --- a/packages/rspack/hot/dev-server.js +++ b/packages/rspack/hot/dev-server.js @@ -3,15 +3,19 @@ Author Tobias Koppers @sokra */ /* globals __webpack_hash__ */ -if (module.hot) { + +import log, { formatError } from './log.js'; +import hotEmitter from './emitter.js'; +import logApplyResult from './log-apply-result.js'; + +if (import.meta.webpackHot) { /** @type {undefined|string} */ var lastHash; var upToDate = function upToDate() { return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0; }; - var log = require('./log'); var check = function check() { - module.hot + import.meta.webpackHot .check(true) .then(function (updatedModules) { if (!updatedModules) { @@ -36,14 +40,14 @@ if (module.hot) { check(); } - require('./log-apply-result')(updatedModules, updatedModules); + logApplyResult(updatedModules, updatedModules); if (upToDate()) { log('info', '[HMR] App is up to date.'); } }) .catch(function (err) { - var status = module.hot.status(); + var status = import.meta.webpackHot.status(); if (['abort', 'fail'].indexOf(status) >= 0) { log( 'warning', @@ -52,19 +56,18 @@ if (module.hot) { ? 'Need to do a full reload!' : 'Please reload manually!'), ); - log('warning', '[HMR] ' + log.formatError(err)); + log('warning', '[HMR] ' + formatError(err)); if (typeof window !== 'undefined') { window.location.reload(); } } else { - log('warning', '[HMR] Update failed: ' + log.formatError(err)); + log('warning', '[HMR] Update failed: ' + formatError(err)); } }); }; - var hotEmitter = require('./emitter'); hotEmitter.on('webpackHotUpdate', function (currentHash) { lastHash = currentHash; - if (!upToDate() && module.hot.status() === 'idle') { + if (!upToDate() && import.meta.webpackHot.status() === 'idle') { log('info', '[HMR] Checking for updates on the server...'); check(); } diff --git a/packages/rspack/hot/emitter.js b/packages/rspack/hot/emitter.js index af41d2ebc7da..aca2cafa962c 100644 --- a/packages/rspack/hot/emitter.js +++ b/packages/rspack/hot/emitter.js @@ -18,4 +18,4 @@ EventEmitter.prototype.emit = function (eventName) { } }; -module.exports = new EventEmitter(); +export default new EventEmitter(); diff --git a/packages/rspack/hot/lazy-compilation-node.js b/packages/rspack/hot/lazy-compilation-node.js index 9ecf07ab958d..5fdfbec6cd10 100644 --- a/packages/rspack/hot/lazy-compilation-node.js +++ b/packages/rspack/hot/lazy-compilation-node.js @@ -1,19 +1,19 @@ +import http from 'http'; +import https from 'https'; + var urlBase = decodeURIComponent(__resourceQuery.slice(1)); /** * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options * @returns {() => void} function to destroy response */ -exports.activate = function (options) { +export const activate = function (options) { var data = options.data; var onError = options.onError; var active = options.active; - var module = options.module; /** @type {import("http").IncomingMessage} */ var response; - var request = ( - urlBase.startsWith('https') ? require('https') : require('http') - ).request( + var request = (urlBase.startsWith('https') ? https : http).request( urlBase + encodeURIComponent(data), { agent: false, @@ -22,7 +22,7 @@ exports.activate = function (options) { function (res) { response = res; response.on('error', errorHandler); - if (!active && !module.hot) { + if (!active && !import.meta.webpackHot) { console.log( 'Hot Module Replacement is not enabled. Waiting for process restart...', ); diff --git a/packages/rspack/hot/lazy-compilation-web.js b/packages/rspack/hot/lazy-compilation-web.js index 28027edaa777..4dbbc6b717c8 100644 --- a/packages/rspack/hot/lazy-compilation-web.js +++ b/packages/rspack/hot/lazy-compilation-web.js @@ -46,11 +46,10 @@ var updateEventSource = function updateEventSource() { * @param {{ data: string, onError: (err: Error) => void, active: boolean, module: module }} options options * @returns {() => void} function to destroy response */ -exports.activate = function (options) { +export const activate = function (options) { var data = options.data; var onError = options.onError; var active = options.active; - var module = options.module; errorHandlers.add(onError); if (!compiling.has(data)) { @@ -58,7 +57,7 @@ exports.activate = function (options) { updateEventSource(); } - if (!active && !module.hot) { + if (!active && !import.meta.webpackHot) { console.log( 'Hot Module Replacement is not enabled. Waiting for process restart...', ); diff --git a/packages/rspack/hot/log-apply-result.js b/packages/rspack/hot/log-apply-result.js index be5e1099a0f8..8f0a3a5b07af 100644 --- a/packages/rspack/hot/log-apply-result.js +++ b/packages/rspack/hot/log-apply-result.js @@ -3,15 +3,16 @@ Author Tobias Koppers @sokra */ +import log, { groupCollapsed, groupEnd } from './log.js'; + /** * @param {(string | number)[]} updatedModules updated modules * @param {(string | number)[] | null} renewedModules renewed modules */ -module.exports = function (updatedModules, renewedModules) { +export default function (updatedModules, renewedModules) { var unacceptedModules = updatedModules.filter(function (moduleId) { return renewedModules && renewedModules.indexOf(moduleId) < 0; }); - var log = require('./log'); if (unacceptedModules.length > 0) { log( @@ -30,9 +31,9 @@ module.exports = function (updatedModules, renewedModules) { renewedModules.forEach(function (moduleId) { if (typeof moduleId === 'string' && moduleId.indexOf('!') !== -1) { var parts = moduleId.split('!'); - log.groupCollapsed('info', '[HMR] - ' + parts.pop()); + groupCollapsed('info', '[HMR] - ' + parts.pop()); log('info', '[HMR] - ' + moduleId); - log.groupEnd('info'); + groupEnd('info'); } else { log('info', '[HMR] - ' + moduleId); } @@ -46,4 +47,4 @@ module.exports = function (updatedModules, renewedModules) { '[HMR] Consider using the optimization.moduleIds: "named" for module names.', ); } -}; +} diff --git a/packages/rspack/hot/log.js b/packages/rspack/hot/log.js index 2d409ed27c4d..13642249de94 100644 --- a/packages/rspack/hot/log.js +++ b/packages/rspack/hot/log.js @@ -33,7 +33,7 @@ function logGroup(logFn) { * @param {LogLevel} level log level * @param {string|Error} msg message */ -module.exports = function (level, msg) { +function log(level, msg) { if (shouldLog(level)) { if (level === 'info') { console.log(msg); @@ -43,22 +43,22 @@ module.exports = function (level, msg) { console.error(msg); } } -}; +} var group = console.group || dummy; var groupCollapsed = console.groupCollapsed || dummy; var groupEnd = console.groupEnd || dummy; -module.exports.group = logGroup(group); +export var group = logGroup(group); -module.exports.groupCollapsed = logGroup(groupCollapsed); +export var groupCollapsed = logGroup(groupCollapsed); -module.exports.groupEnd = logGroup(groupEnd); +export var groupEnd = logGroup(groupEnd); /** * @param {LogLevel} level log level */ -module.exports.setLogLevel = function (level) { +export var setLogLevel = function (level) { logLevel = level; }; @@ -66,7 +66,7 @@ module.exports.setLogLevel = function (level) { * @param {Error} err error * @returns {string} formatted error */ -module.exports.formatError = function (err) { +export var formatError = function (err) { var message = err.message; var stack = err.stack; if (!stack) { @@ -77,3 +77,11 @@ module.exports.formatError = function (err) { return stack; } }; + +log.group = group; +log.groupCollapsed = groupCollapsed; +log.groupEnd = groupEnd; +log.setLogLevel = setLogLevel; +log.formatError = formatError; + +export default log; diff --git a/packages/rspack/hot/only-dev-server.js b/packages/rspack/hot/only-dev-server.js index 28b6f789ca6f..b3356c4ef329 100644 --- a/packages/rspack/hot/only-dev-server.js +++ b/packages/rspack/hot/only-dev-server.js @@ -3,15 +3,19 @@ Author Tobias Koppers @sokra */ /*globals __webpack_hash__ */ -if (module.hot) { + +import log, { formatError } from './log.js'; +import hotEmitter from './emitter.js'; +import logApplyResult from './log-apply-result.js'; + +if (import.meta.webpackHot) { /** @type {undefined|string} */ var lastHash; var upToDate = function upToDate() { return /** @type {string} */ (lastHash).indexOf(__webpack_hash__) >= 0; }; - var log = require('./log'); var check = function check() { - module.hot + import.meta.webpackHot .check() .then(function (updatedModules) { if (!updatedModules) { @@ -23,7 +27,7 @@ if (module.hot) { return; } - return module.hot + return import.meta.webpackHot .apply({ ignoreUnaccepted: true, ignoreDeclined: true, @@ -59,7 +63,7 @@ if (module.hot) { check(); } - require('./log-apply-result')(updatedModules, renewedModules); + logApplyResult(updatedModules, renewedModules); if (upToDate()) { log('info', '[HMR] App is up to date.'); @@ -67,23 +71,22 @@ if (module.hot) { }); }) .catch(function (err) { - var status = module.hot.status(); + var status = import.meta.webpackHot.status(); if (['abort', 'fail'].indexOf(status) >= 0) { log( 'warning', '[HMR] Cannot check for update. Need to do a full reload!', ); - log('warning', '[HMR] ' + log.formatError(err)); + log('warning', '[HMR] ' + formatError(err)); } else { - log('warning', '[HMR] Update check failed: ' + log.formatError(err)); + log('warning', '[HMR] Update check failed: ' + formatError(err)); } }); }; - var hotEmitter = require('./emitter'); hotEmitter.on('webpackHotUpdate', function (currentHash) { lastHash = currentHash; if (!upToDate()) { - var status = module.hot.status(); + var status = import.meta.webpackHot.status(); if (status === 'idle') { log('info', '[HMR] Checking for updates on the server...'); check(); diff --git a/packages/rspack/hot/poll.js b/packages/rspack/hot/poll.js index 72a98a912c73..ae97307af47e 100644 --- a/packages/rspack/hot/poll.js +++ b/packages/rspack/hot/poll.js @@ -3,33 +3,36 @@ Author Tobias Koppers @sokra */ /*globals __resourceQuery */ -if (module.hot) { + +import log, { formatError } from './log.js'; +import logApplyResult from './log-apply-result.js'; + +if (import.meta.webpackHot) { var hotPollInterval = +__resourceQuery.slice(1) || 10 * 60 * 1000; - var log = require('./log'); /** * @param {boolean=} fromUpdate true when called from update */ var checkForUpdate = function checkForUpdate(fromUpdate) { - if (module.hot.status() === 'idle') { - module.hot + if (import.meta.webpackHot.status() === 'idle') { + import.meta.webpackHot .check(true) .then(function (updatedModules) { if (!updatedModules) { if (fromUpdate) log('info', '[HMR] Update applied.'); return; } - require('./log-apply-result')(updatedModules, updatedModules); + logApplyResult(updatedModules, updatedModules); checkForUpdate(true); }) .catch(function (err) { - var status = module.hot.status(); + var status = import.meta.webpackHot.status(); if (['abort', 'fail'].indexOf(status) >= 0) { log('warning', '[HMR] Cannot apply update.'); - log('warning', '[HMR] ' + log.formatError(err)); + log('warning', '[HMR] ' + formatError(err)); log('warning', '[HMR] You need to restart the application!'); } else { - log('warning', '[HMR] Update failed: ' + log.formatError(err)); + log('warning', '[HMR] Update failed: ' + formatError(err)); } }); } diff --git a/packages/rspack/hot/signal.js b/packages/rspack/hot/signal.js index 2422d79203a4..99f249792425 100644 --- a/packages/rspack/hot/signal.js +++ b/packages/rspack/hot/signal.js @@ -3,14 +3,16 @@ Author Tobias Koppers @sokra */ /*globals __resourceQuery */ -if (module.hot) { - var log = require('./log'); +import log, { formatError } from './log.js'; +import logApplyResult from './log-apply-result.js'; + +if (import.meta.webpackHot) { /** * @param {boolean=} fromUpdate true when called from update */ var checkForUpdate = function checkForUpdate(fromUpdate) { - module.hot + import.meta.webpackHot .check() .then(function (updatedModules) { if (!updatedModules) { @@ -19,7 +21,7 @@ if (module.hot) { return; } - return module.hot + return import.meta.webpackHot .apply({ ignoreUnaccepted: true, onUnaccepted: function (data) { @@ -31,17 +33,17 @@ if (module.hot) { }, }) .then(function (renewedModules) { - require('./log-apply-result')(updatedModules, renewedModules); + logApplyResult(updatedModules, renewedModules); checkForUpdate(true); return null; }); }) .catch(function (err) { - var status = module.hot.status(); + var status = import.meta.webpackHot.status(); if (['abort', 'fail'].indexOf(status) >= 0) { log('warning', '[HMR] Cannot apply update.'); - log('warning', '[HMR] ' + log.formatError(err)); + log('warning', '[HMR] ' + formatError(err)); log('warning', '[HMR] You need to restart the application!'); } else { log('warning', '[HMR] Update failed: ' + (err.stack || err.message)); @@ -50,10 +52,12 @@ if (module.hot) { }; process.on(__resourceQuery.slice(1) || 'SIGUSR2', function () { - if (module.hot.status() !== 'idle') { + if (import.meta.webpackHot.status() !== 'idle') { log( 'warning', - '[HMR] Got signal but currently in ' + module.hot.status() + ' state.', + '[HMR] Got signal but currently in ' + + import.meta.webpackHot.status() + + ' state.', ); log('warning', '[HMR] Need to be in idle state to start hot update.'); return; diff --git a/packages/rspack/move-tinypool.js b/packages/rspack/move-tinypool.js index 3c56e557d835..cbb99f0377fe 100644 --- a/packages/rspack/move-tinypool.js +++ b/packages/rspack/move-tinypool.js @@ -1,11 +1,12 @@ // This script copies the tinypool package from node_modules to the compiled directory. // It removes the engines field from package.json and ensures that the package is working under `engine-strict=true` on lower node versions. +import fs from 'node:fs'; +import { createRequire } from 'node:module'; +import path from 'node:path'; -const fs = require('node:fs'); -const path = require('node:path'); - +const require = createRequire(import.meta.url); const tinypool = path.dirname(require.resolve('tinypool/package.json')); -const dest = path.resolve(__dirname, './compiled/tinypool'); +const dest = path.resolve(import.meta.dirname, './compiled/tinypool'); fs.cpSync(tinypool, dest, { recursive: true, force: true }); diff --git a/packages/rspack/package.json b/packages/rspack/package.json index c04808e12869..b025d063a105 100644 --- a/packages/rspack/package.json +++ b/packages/rspack/package.json @@ -4,12 +4,12 @@ "webpackVersion": "5.75.0", "license": "MIT", "description": "The fast Rust-based web bundler with webpack-compatible API", - "main": "./dist/index.js", "types": "./dist/index.d.ts", "publishConfig": { "access": "public", "provenance": true }, + "type": "module", "exports": { ".": { "types": "./dist/index.d.ts", @@ -23,7 +23,7 @@ "scripts": { "prepare": "prebundle && node ./move-tinypool.js", "build": "rslib build", - "build:browser": "rslib build -c rslib.browser.config.mts", + "build:browser": "rslib build -c rslib.browser.config.ts", "dev": "rslib build --watch", "doc-coverage": "tsx ./scripts/check-documentation-coverage.ts", "api-extractor": "api-extractor run --verbose", @@ -36,7 +36,7 @@ "module.d.ts" ], "engines": { - "node": ">=18.12.0" + "node": "^20.19.0 || >=22.12.0" }, "homepage": "https://rspack.rs", "bugs": "https://github.com/web-infra-dev/rspack/issues", diff --git a/packages/rspack/rslib.browser.config.mts b/packages/rspack/rslib.browser.config.ts similarity index 80% rename from packages/rspack/rslib.browser.config.mts rename to packages/rspack/rslib.browser.config.ts index 2d1a16262fd5..cc891b8e3657 100644 --- a/packages/rspack/rslib.browser.config.mts +++ b/packages/rspack/rslib.browser.config.ts @@ -2,7 +2,8 @@ import fs from 'node:fs/promises'; import path from 'node:path'; import vm from 'node:vm'; import { pluginNodePolyfill } from '@rsbuild/plugin-node-polyfill'; -import { defineConfig, type rsbuild, rspack } from '@rslib/core'; +import { defineConfig, type RsbuildPlugin, rspack } from '@rslib/core'; +import packageJson from './package.json' with { type: 'json' }; const bindingDir = path.resolve('../../crates/node_binding'); const distDir = path.resolve('../rspack-browser/dist'); @@ -13,8 +14,13 @@ export default defineConfig({ lib: [ { format: 'esm', - syntax: 'es2021', + syntax: 'es2023', dts: { build: true }, + redirect: { + dts: { + extension: true, + }, + }, autoExternal: false, source: { entry: { @@ -24,7 +30,7 @@ export default defineConfig({ }, { format: 'esm', - syntax: 'es2021', + syntax: 'es2023', dts: false, autoExtension: false, source: { @@ -82,24 +88,17 @@ export default defineConfig({ source: { tsconfigPath: './tsconfig.browser.json', define: { - WEBPACK_VERSION: JSON.stringify(require('./package.json').webpackVersion), - RSPACK_VERSION: JSON.stringify(require('./package.json').version), + WEBPACK_VERSION: JSON.stringify(packageJson.webpackVersion), + RSPACK_VERSION: JSON.stringify(packageJson.version), IS_BROWSER: JSON.stringify(true), // In `@rspack/browser`, runtime code like loaders and hmr should be written into something like memfs ahead of time. // Requiring these files should resolve to `@rspack/browser/xx` - __dirname: JSON.stringify('@rspack/browser'), + 'import.meta.dirname': JSON.stringify('@rspack/browser'), // Runtime code MF_RUNTIME_CODE: JSON.stringify(MF_RUNTIME_CODE), }, }, tools: { - bundlerChain: (chain, { CHAIN_ID }) => { - // remove the entry loader in Rslib to avoid - // "Cannot access 'Compiler' before initialization" error caused by circular dependency - chain.module - .rule(`Rslib:${CHAIN_ID.RULE.JS}-entry-loader`) - .uses.delete('rsbuild:lib-entry-module'); - }, rspack: (config, { rspack }) => { config.plugins.push( new rspack.IgnorePlugin({ @@ -122,7 +121,7 @@ export default defineConfig({ * 1. Wraps `new Worker("./wasi-worker-browser.mjs", import.meta.url)` inside `importScripts`. * 2. Retrieves the WebAssembly module URL from the global variable `window.RSPACK_WASM_URL`. */ -function copyRspackBrowserRuntimePlugin(): rsbuild.RsbuildPlugin { +function copyRspackBrowserRuntimePlugin(): RsbuildPlugin { return { name: 'copy-rspack-browser-runtime-plugin', setup(api) { @@ -162,7 +161,7 @@ function copyRspackBrowserRuntimePlugin(): rsbuild.RsbuildPlugin { * The reason that we don't use `paths` in `tsconfig.json` is that it can't rewrite the module idents in `declare module`, * so we decided to simply replace all instances of it. */ -function replaceDtsPlugin(): rsbuild.RsbuildPlugin { +function replaceDtsPlugin(): RsbuildPlugin { return { name: 'replace-dts-plugin', setup(api) { @@ -187,21 +186,21 @@ function replaceDtsPlugin(): rsbuild.RsbuildPlugin { } // There are three cases that @rspack/binding may be used - // 1. import("@rspack/binding").XXX - // 2. import { XX } from "@rspack/binding" - // 3. declare module "@rspack/binding" { XX } + // 1. import('@rspack/binding').XXX + // 2. import { XX } from '@rspack/binding' + // 3. declare module '@rspack/binding' { XX } const replacedDts = dts .replaceAll( - 'import("@rspack/binding")', - `import("${relativeBindingDts}")`, + `import('@rspack/binding')`, + `import('${relativeBindingDts}')`, ) .replaceAll( - 'from "@rspack/binding"', - `from "${relativeBindingDts}"`, + `from '@rspack/binding'`, + `from '${relativeBindingDts}'`, ) .replaceAll( - 'declare module "@rspack/binding"', - `declare module "${relativeBindingDts}"`, + `declare module '@rspack/binding'`, + `declare module '${relativeBindingDts}'`, ); await fs.writeFile(filePath, replacedDts); } @@ -220,6 +219,12 @@ async function getModuleFederationRuntimeCode() { const { code: downgradedRuntime } = await swc.transform(runtime, { jsc: { target: 'es2015', + parser: { + syntax: 'ecmascript', + }, + }, + module: { + type: 'commonjs', }, }); @@ -229,12 +234,27 @@ async function getModuleFederationRuntimeCode() { ecma: 2015, }); - const sandbox = { module: { exports: undefined } } as any; + const exports = {}; + const module = { exports }; + const sandbox = { + module, + exports, + console, + }; + vm.createContext(sandbox); vm.runInContext(minimizedRuntime.code, sandbox); - const functionContent = rspack.Template.getFunctionContent( - sandbox.module.exports, - ); + // @ts-expect-error + const runtimeExport = module.exports.default || module.exports; + + const originalToString = runtimeExport.toString; + runtimeExport.toString = function () { + return originalToString + .call(this) + .replace(/^function\s+[\w$]+/, 'function'); + }; + + const functionContent = rspack.Template.getFunctionContent(runtimeExport); return functionContent; } diff --git a/packages/rspack/rslib.config.mts b/packages/rspack/rslib.config.ts similarity index 54% rename from packages/rspack/rslib.config.mts rename to packages/rspack/rslib.config.ts index e1a38d48793e..e5a01796d364 100644 --- a/packages/rspack/rslib.config.mts +++ b/packages/rspack/rslib.config.ts @@ -1,19 +1,33 @@ import fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { type Edit, Lang, parse, type SgNode } from '@ast-grep/napi'; import type { Kinds, TypesMap } from '@ast-grep/napi/types/staticTypes'; -import { defineConfig, type LibConfig, rsbuild, rspack } from '@rslib/core'; +import { + defineConfig, + type LibConfig, + type RsbuildPlugin, + type Rspack, + rsbuild, + rspack, +} from '@rslib/core'; +import packageJson from './package.json' with { type: 'json' }; import prebundleConfig from './prebundle.config.mjs'; +const require = createRequire(import.meta.url); + const merge = rsbuild.mergeRsbuildConfig; -const externalAlias: rsbuild.Rspack.Externals = ({ request }, callback) => { +const externalAlias: Rspack.Externals = ({ request }, callback) => { const { dependencies } = prebundleConfig; for (const item of dependencies) { const depName = typeof item === 'string' ? item : item.name; if (new RegExp(`^${depName}$`).test(request!)) { - return callback(undefined, `../compiled/${depName}/index.js`); + return callback( + undefined, + `node-commonjs ../compiled/${depName}/index.js`, + ); } } @@ -25,17 +39,24 @@ const externalAlias: rsbuild.Rspack.Externals = ({ request }, callback) => { }; const commonLibConfig: LibConfig = { - format: 'cjs', - syntax: ['node 18.12'], + format: 'esm', + syntax: ['es2023'], source: { define: { - WEBPACK_VERSION: JSON.stringify(require('./package.json').webpackVersion), - RSPACK_VERSION: JSON.stringify(require('./package.json').version), + WEBPACK_VERSION: JSON.stringify(packageJson.webpackVersion), + RSPACK_VERSION: JSON.stringify(packageJson.version), IS_BROWSER: JSON.stringify(false), }, }, output: { - externals: ['@rspack/binding/package.json', externalAlias], + externals: [ + { + '@rspack/binding': 'node-commonjs @rspack/binding', + }, + './moduleFederationDefaultRuntime.js', + '@rspack/binding/package.json', + externalAlias, + ], minify: { js: true, jsOptions: { @@ -55,14 +76,14 @@ const commonLibConfig: LibConfig = { }, }; -const mfRuntimePlugin: rsbuild.RsbuildPlugin = { +const mfRuntimePlugin: RsbuildPlugin = { name: 'mf-runtime', setup(api) { api.onAfterBuild(async () => { const { swc } = rspack.experiments; const runtime = await fs.promises.readFile( path.resolve( - __dirname, + import.meta.dirname, 'src/runtime/moduleFederationDefaultRuntime.js', ), 'utf-8', @@ -81,42 +102,66 @@ const mfRuntimePlugin: rsbuild.RsbuildPlugin = { }); await fs.promises.writeFile( - path.resolve(__dirname, 'dist/moduleFederationDefaultRuntime.js'), + path.resolve( + import.meta.dirname, + 'dist/moduleFederationDefaultRuntime.js', + ), minimizedRuntime.code, ); }); }, }; -const codmodPlugin: rsbuild.RsbuildPlugin = { +const codmodPlugin: RsbuildPlugin = { name: 'codmod', setup(api) { /** * Replaces `@rspack/binding` to code that reads env `RSPACK_BINDING` as the custom binding. */ function replaceBinding(root: SgNode>): Edit[] { - const target = `module1.exports = require("@rspack/binding");`; - const binding = root.find(target); - if (binding === null) { - throw new Error('Cannot find binding require statement: ' + target); + const edits: Edit[] = []; + + // Pattern 1: let binding_namespaceObject = __rspack_createRequire_require("@rspack/binding"); + const pattern1 = `let binding_namespaceObject = __rspack_createRequire_require("@rspack/binding");`; + const binding1 = root.find(pattern1); + if (binding1) { + edits.push( + binding1.replace( + `let binding_namespaceObject = __rspack_createRequire_require(process.env.RSPACK_BINDING ? process.env.RSPACK_BINDING : "@rspack/binding");`, + ), + ); } - return [ - binding.replace( - `module1.exports = require(process.env.RSPACK_BINDING ? process.env.RSPACK_BINDING : "@rspack/binding");`, - ), - ]; + + // Pattern 2: let instanceBinding = Compiler_require('@rspack/binding'); + const pattern2 = `let instanceBinding = Compiler_require('@rspack/binding');`; + const binding2 = root.find(pattern2); + if (binding2) { + edits.push( + binding2.replace( + `let instanceBinding = Compiler_require(process.env.RSPACK_BINDING ? process.env.RSPACK_BINDING : '@rspack/binding');`, + ), + ); + } + + if (edits.length === 0) { + throw new Error( + 'Cannot find any binding require statements to replace', + ); + } + + return edits; } api.onAfterBuild(async () => { const dist = fs.readFileSync( - require.resolve(path.resolve(__dirname, 'dist/index.js')), + require.resolve(path.resolve(import.meta.dirname, 'dist/index.js')), 'utf-8', ); const root = parse(Lang.JavaScript, dist).root(); const edits = [...replaceBinding(root)]; fs.writeFileSync( - require.resolve(path.resolve(__dirname, 'dist/index.js')), + require.resolve(path.resolve(import.meta.dirname, 'dist/index.js')), root.commitEdits(edits), ); }); @@ -130,6 +175,11 @@ export default defineConfig({ dts: { build: true, }, + redirect: { + dts: { + extension: true, + }, + }, source: { entry: { index: './src/index.ts', @@ -139,9 +189,19 @@ export default defineConfig({ output: { externals: [externalAlias, './moduleFederationDefaultRuntime.js'], }, - footer: { - // make default export in cjs work - js: 'module.exports = __webpack_exports__.default;', + tools: { + rspack: { + plugins: [ + new rspack.BannerPlugin({ + // make require esm default export compatible with commonjs + banner: `export { src_rspack_0 as 'module.exports' }`, + stage: rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1, + raw: true, + footer: true, + include: /index\.js$/, + }), + ], + }, }, }), merge(commonLibConfig, { @@ -165,10 +225,6 @@ export default defineConfig({ worker: './src/loader-runner/worker.ts', }, }, - footer: { - // make default export in cjs work - js: 'module.exports = __webpack_exports__.default;', - }, }), ], }); diff --git a/packages/rspack/src/Compiler.ts b/packages/rspack/src/Compiler.ts index 327ec6bf301e..42a9cd4b0e3a 100644 --- a/packages/rspack/src/Compiler.ts +++ b/packages/rspack/src/Compiler.ts @@ -7,6 +7,8 @@ * Copyright (c) JS Foundation and other contributors * https://github.com/webpack/webpack/blob/main/LICENSE */ + +import { createRequire } from 'node:module'; import type binding from '@rspack/binding'; import * as liteTapable from '@rspack/lite-tapable'; import type Watchpack from 'watchpack'; @@ -17,7 +19,6 @@ import { JsLoaderRspackPlugin, } from './builtin-plugin'; import { canInherentFromParent } from './builtin-plugin/base'; - import type { Chunk } from './Chunk'; import type { CompilationParams } from './Compilation'; import { Compilation } from './Compilation'; @@ -73,6 +74,8 @@ import { makePathsRelative } from './util/identifier'; import { VirtualModulesPlugin } from './VirtualModulesPlugin'; import { Watching } from './Watching'; +const require = createRequire(import.meta.url); + export interface AssetEmittedInfo { content: Buffer; source: Source; diff --git a/packages/rspack/src/ExecuteModulePlugin.ts b/packages/rspack/src/ExecuteModulePlugin.ts index f32556a17e2b..c2a88dfc8d32 100644 --- a/packages/rspack/src/ExecuteModulePlugin.ts +++ b/packages/rspack/src/ExecuteModulePlugin.ts @@ -1,6 +1,9 @@ +import { createRequire } from 'node:module'; import type { Compiler } from './Compiler'; import { RuntimeVariable, renderRuntimeVariables } from './RuntimeGlobals'; +const require = createRequire(import.meta.url); + export default class ExecuteModulePlugin { apply(compiler: Compiler) { compiler.hooks.thisCompilation.tap('executeModule', (compilation) => { diff --git a/packages/rspack/src/builtin-plugin/EsmLibraryPlugin.ts b/packages/rspack/src/builtin-plugin/EsmLibraryPlugin.ts index 217ea6b8be5f..44274d91dc1d 100644 --- a/packages/rspack/src/builtin-plugin/EsmLibraryPlugin.ts +++ b/packages/rspack/src/builtin-plugin/EsmLibraryPlugin.ts @@ -1,7 +1,7 @@ import { BuiltinPluginName } from '@rspack/binding'; -import rspack from '..'; import type { Compiler } from '../Compiler'; import type { RspackOptionsNormalized } from '../config'; +import WebpackError from '../lib/WebpackError'; import type { Logger } from '../logging/Logger'; import { RemoveDuplicateModulesPlugin } from './RemoveDuplicateModulesPlugin'; @@ -66,7 +66,7 @@ export class EsmLibraryPlugin { let err; if ((err = checkConfig(compiler.options))) { - throw new rspack.WebpackError( + throw new WebpackError( `Conflicted config for ${EsmLibraryPlugin.PLUGIN_NAME}: ${err}`, ); } diff --git a/packages/rspack/src/builtin-plugin/HttpUriPlugin.ts b/packages/rspack/src/builtin-plugin/HttpUriPlugin.ts index bf50605f8b95..701dc14eefca 100644 --- a/packages/rspack/src/builtin-plugin/HttpUriPlugin.ts +++ b/packages/rspack/src/builtin-plugin/HttpUriPlugin.ts @@ -1,4 +1,5 @@ import type { IncomingMessage } from 'node:http'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { type BuiltinPlugin, @@ -8,6 +9,9 @@ import { import type { Compiler } from '../Compiler'; import { memoize } from '../util/memoize'; import { createBuiltinPlugin, RspackBuiltinPlugin } from './base'; + +const require = createRequire(import.meta.url); + export type HttpUriPluginOptionsAllowedUris = (string | RegExp)[]; export type HttpUriPluginOptions = { diff --git a/packages/rspack/src/builtin-plugin/SubresourceIntegrityPlugin.ts b/packages/rspack/src/builtin-plugin/SubresourceIntegrityPlugin.ts index 1e9799285690..fc16bf03c3e0 100644 --- a/packages/rspack/src/builtin-plugin/SubresourceIntegrityPlugin.ts +++ b/packages/rspack/src/builtin-plugin/SubresourceIntegrityPlugin.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; import { join, relative, sep } from 'node:path'; import { BuiltinPluginName, @@ -11,6 +12,8 @@ import type { Compiler } from '../Compiler'; import type { CrossOriginLoading } from '../config/types'; import { create } from './base'; +const require = createRequire(import.meta.url); + const PLUGIN_NAME = 'SubresourceIntegrityPlugin'; const NATIVE_HTML_PLUGIN = 'HtmlRspackPlugin'; diff --git a/packages/rspack/src/builtin-plugin/css-extract/index.ts b/packages/rspack/src/builtin-plugin/css-extract/index.ts index bb7cb24ba27f..2aea9544a78d 100644 --- a/packages/rspack/src/builtin-plugin/css-extract/index.ts +++ b/packages/rspack/src/builtin-plugin/css-extract/index.ts @@ -10,7 +10,7 @@ import { PLUGIN_NAME } from './utils'; export * from './loader'; const DEFAULT_FILENAME = '[name].css'; -const LOADER_PATH = join(__dirname, 'cssExtractLoader.js'); +const LOADER_PATH = join(import.meta.dirname, 'cssExtractLoader.js'); export type { CssExtractRspackLoaderOptions } from './loader'; diff --git a/packages/rspack/src/builtin-plugin/css-extract/loader.ts b/packages/rspack/src/builtin-plugin/css-extract/loader.ts index 1804b75e932e..faa37a75bc65 100644 --- a/packages/rspack/src/builtin-plugin/css-extract/loader.ts +++ b/packages/rspack/src/builtin-plugin/css-extract/loader.ts @@ -46,7 +46,7 @@ export function hotLoader( // ${Date.now()} var cssReload = require(${stringifyRequest( context.loaderContext, - path.join(__dirname, 'cssExtractHmr.js'), + path.join(import.meta.dirname, 'cssExtractHmr.js'), )}).cssReload(module.id, ${JSON.stringify(context.options ?? {})}); // only invalidate when locals change if ( diff --git a/packages/rspack/src/builtin-plugin/html-plugin/plugin.ts b/packages/rspack/src/builtin-plugin/html-plugin/plugin.ts index d2dcafeef30c..56c9f927583a 100644 --- a/packages/rspack/src/builtin-plugin/html-plugin/plugin.ts +++ b/packages/rspack/src/builtin-plugin/html-plugin/plugin.ts @@ -1,11 +1,11 @@ import fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import { BuiltinPluginName, type JsHtmlPluginTag, type RawHtmlRspackPluginOptions, } from '@rspack/binding'; - import type { Compilation } from '../../Compilation'; import type { Compiler } from '../../Compiler'; import { create } from '../base'; @@ -20,6 +20,8 @@ import { setPluginOptions, } from './options'; +const require = createRequire(import.meta.url); + type HtmlPluginTag = { tagName: string; attributes: Record; diff --git a/packages/rspack/src/builtin-plugin/lazy-compilation/lazyCompilation.ts b/packages/rspack/src/builtin-plugin/lazy-compilation/lazyCompilation.ts index f606ded22907..c68acb80b091 100644 --- a/packages/rspack/src/builtin-plugin/lazy-compilation/lazyCompilation.ts +++ b/packages/rspack/src/builtin-plugin/lazy-compilation/lazyCompilation.ts @@ -11,6 +11,6 @@ export const BuiltinLazyCompilationPlugin = create( imports: boolean, client: string, test?: RegExp | ((module: Module) => boolean), - ) => ({ module, imports, entries, test, client, currentActiveModules }), + ) => ({ imports, entries, test, client, currentActiveModules }), 'thisCompilation', ); diff --git a/packages/rspack/src/builtin-plugin/lazy-compilation/middleware.ts b/packages/rspack/src/builtin-plugin/lazy-compilation/middleware.ts index 5a0367834cfe..2a39aa3c07bf 100644 --- a/packages/rspack/src/builtin-plugin/lazy-compilation/middleware.ts +++ b/packages/rspack/src/builtin-plugin/lazy-compilation/middleware.ts @@ -1,9 +1,12 @@ import type { IncomingMessage, ServerResponse } from 'node:http'; +import { createRequire } from 'node:module'; import { type Compiler, MultiCompiler } from '../..'; import type { LazyCompilationOptions } from '../../config'; import type { MiddlewareHandler } from '../../config/devServer'; import { BuiltinLazyCompilationPlugin } from './lazyCompilation'; +const require = createRequire(import.meta.url); + export const LAZY_COMPILATION_PREFIX = '/lazy-compilation-using-'; const getDefaultClient = (compiler: Compiler): string => diff --git a/packages/rspack/src/config/target.ts b/packages/rspack/src/config/target.ts index 54344a076680..454dfb9ef21d 100644 --- a/packages/rspack/src/config/target.ts +++ b/packages/rspack/src/config/target.ts @@ -1,3 +1,4 @@ +import { createRequire } from 'node:module'; import binding from '@rspack/binding'; /** * The following code is modified based on @@ -11,6 +12,8 @@ import binding from '@rspack/binding'; import { memoize } from '../util/memoize'; import * as browserslistTargetHandler from './browserslistTargetHandler'; +const require = createRequire(import.meta.url); + const getBrowserslistTargetHandler = memoize(() => browserslistTargetHandler); const hasBrowserslistConfig = (context: string) => { diff --git a/packages/rspack/src/container/ModuleFederationPlugin.ts b/packages/rspack/src/container/ModuleFederationPlugin.ts index 0f0cb5bf0363..a98bc9196986 100644 --- a/packages/rspack/src/container/ModuleFederationPlugin.ts +++ b/packages/rspack/src/container/ModuleFederationPlugin.ts @@ -1,3 +1,4 @@ +import { createRequire } from 'node:module'; import type { Compiler } from '../Compiler'; import type { ExternalsType } from '../config'; import type { SharedConfig } from '../sharing/SharePlugin'; @@ -13,6 +14,8 @@ import type { ModuleFederationPluginV1Options } from './ModuleFederationPluginV1 import { ModuleFederationRuntimePlugin } from './ModuleFederationRuntimePlugin'; import { parseOptions } from './options'; +const require = createRequire(import.meta.url); + declare const MF_RUNTIME_CODE: string; export interface ModuleFederationPluginOptions extends Omit< @@ -367,7 +370,7 @@ function getDefaultEntryRuntime( IS_BROWSER ? MF_RUNTIME_CODE : compiler.webpack.Template.getFunctionContent( - require('./moduleFederationDefaultRuntime.js'), + require('./moduleFederationDefaultRuntime.js').default, ), ].join(';'); return `@module-federation/runtime/rspack.js!=!data:text/javascript,${content}`; diff --git a/packages/rspack/src/exports.ts b/packages/rspack/src/exports.ts index 5b8a542b5f6e..9e17f786e950 100644 --- a/packages/rspack/src/exports.ts +++ b/packages/rspack/src/exports.ts @@ -65,7 +65,7 @@ export const WebpackError = Error; export type { Watching } from './Watching'; -import sources = require('webpack-sources'); +import * as sources from 'webpack-sources'; export { sources }; diff --git a/packages/rspack/src/index.ts b/packages/rspack/src/index.ts index d2c91e91bdff..e5ef254d7df2 100644 --- a/packages/rspack/src/index.ts +++ b/packages/rspack/src/index.ts @@ -11,4 +11,4 @@ const rspack: Rspack = fn; export * from './exports'; export default rspack; -export { rspack }; +export { rspack, rspack as webpack }; diff --git a/packages/rspack/src/loader-runner/loadLoader.ts b/packages/rspack/src/loader-runner/loadLoader.ts index ab1bed2ecb26..b9a4add6b9bc 100644 --- a/packages/rspack/src/loader-runner/loadLoader.ts +++ b/packages/rspack/src/loader-runner/loadLoader.ts @@ -8,6 +8,7 @@ * https://github.com/webpack/loader-runner/blob/main/LICENSE */ +import { createRequire } from 'node:module'; import type Url from 'node:url'; import type { LoaderDefinitionFunction } from '../config'; import type { PitchLoaderDefinitionFunction } from '../config/adapterRuleUse'; @@ -15,6 +16,8 @@ import type { Compiler } from '../exports'; import type { LoaderObject } from '.'; import LoaderLoadingError from './LoaderLoadingError'; +const require = createRequire(import.meta.url); + type ModuleObject = { default?: LoaderDefinitionFunction; pitch?: PitchLoaderDefinitionFunction; diff --git a/packages/rspack/src/loader-runner/service.ts b/packages/rspack/src/loader-runner/service.ts index fcfc522d3752..6f40aea5a5be 100644 --- a/packages/rspack/src/loader-runner/service.ts +++ b/packages/rspack/src/loader-runner/service.ts @@ -1,7 +1,10 @@ +import { createRequire } from 'node:module'; import path from 'node:path'; // biome-ignore syntax/correctness/noTypeOnlyImportAttributes: Biome does not support this import type { Tinypool } from 'tinypool' with { 'resolution-mode': 'import' }; +const require = createRequire(import.meta.url); + let pool: Promise | undefined; const ensureLoaderWorkerPool = async (workerOptions?: { maxWorkers?: number; @@ -21,7 +24,7 @@ const ensureLoaderWorkerPool = async (workerOptions?: { ); const pool = new Tinypool({ - filename: path.resolve(__dirname, 'worker.js'), + filename: path.resolve(import.meta.dirname, 'worker.js'), useAtomics: false, maxThreads: maxWorkers || maxWorkersFromEnv || availableThreads, diff --git a/packages/rspack/src/loader-runner/worker.ts b/packages/rspack/src/loader-runner/worker.ts index d3d91eb28db2..51182387b238 100644 --- a/packages/rspack/src/loader-runner/worker.ts +++ b/packages/rspack/src/loader-runner/worker.ts @@ -1,10 +1,12 @@ +import fs from 'node:fs'; import querystring from 'node:querystring'; import { promisify } from 'node:util'; import { type MessagePort, receiveMessageOnPort } from 'node:worker_threads'; import { JsLoaderState, type NormalModule } from '@rspack/binding'; import type { LoaderContext } from '../config'; - +import * as swc from '../swc'; +import { cleverMerge } from '../util/cleverMerge'; import { createHash } from '../util/createHash'; import { absolutify, contextify } from '../util/identifier'; import { memoize } from '../util/memoize'; @@ -249,14 +251,14 @@ async function loaderImpl( rspack: { // @ts-expect-error: some properties are missing. experiments: { - swc: require('../swc'), + swc, }, }, // @ts-expect-error: some properties are missing. webpack: { util: { - createHash: require('../util/createHash').createHash, - cleverMerge: require('../util/cleverMerge').cleverMerge, + createHash, + cleverMerge, }, }, }; @@ -329,7 +331,7 @@ async function loaderImpl( ); }; - loaderContext.fs = require('node:fs'); + loaderContext.fs = fs; Object.defineProperty(loaderContext, 'request', { enumerable: true, diff --git a/packages/rspack/src/node/NodeWatchFileSystem.ts b/packages/rspack/src/node/NodeWatchFileSystem.ts index 48ce8f3c68eb..e81c780287c5 100644 --- a/packages/rspack/src/node/NodeWatchFileSystem.ts +++ b/packages/rspack/src/node/NodeWatchFileSystem.ts @@ -8,6 +8,7 @@ * https://github.com/webpack/webpack/blob/main/LICENSE */ +import { createRequire } from 'node:module'; import util from 'node:util'; import type Watchpack from 'watchpack'; @@ -18,6 +19,8 @@ import type { WatchFileSystem, } from '../util/fs'; +const require = createRequire(import.meta.url); + export default class NodeWatchFileSystem implements WatchFileSystem { inputFileSystem: InputFileSystem; watcherOptions: Watchpack.WatchOptions; diff --git a/packages/rspack/src/runtime/moduleFederationDefaultRuntime.js b/packages/rspack/src/runtime/moduleFederationDefaultRuntime.js index b735f7823de5..dc220bbb1e73 100644 --- a/packages/rspack/src/runtime/moduleFederationDefaultRuntime.js +++ b/packages/rspack/src/runtime/moduleFederationDefaultRuntime.js @@ -4,7 +4,7 @@ var __module_federation_bundler_runtime__, __module_federation_remote_infos__, __module_federation_container_name__, __module_federation_share_strategy__; -module.exports = function () { +export default function () { if ( (__webpack_require__.initializeSharingData || __webpack_require__.initializeExposesData) && @@ -288,4 +288,4 @@ module.exports = function () { }); } } -}; +} diff --git a/packages/rspack/src/util/createHash.ts b/packages/rspack/src/util/createHash.ts index 732cb7e91477..23998ce4eb72 100644 --- a/packages/rspack/src/util/createHash.ts +++ b/packages/rspack/src/util/createHash.ts @@ -8,10 +8,13 @@ * https://github.com/webpack/webpack/blob/main/LICENSE */ +import { createRequire } from 'node:module'; import Hash from './hash'; import createMd4 from './hash/md4'; import createXXHash64 from './hash/xxhash64'; +const require = createRequire(import.meta.url); + const BULK_SIZE = 2000; // We are using an object instead of a Map as this will stay static during the runtime diff --git a/packages/rspack/tsconfig.browser.json b/packages/rspack/tsconfig.browser.json index c2891006577f..a5e3b74b8fd9 100644 --- a/packages/rspack/tsconfig.browser.json +++ b/packages/rspack/tsconfig.browser.json @@ -4,6 +4,8 @@ "outDir": "../rspack-browser/dist", "rootDir": "src", "lib": ["es2022", "dom"], + "module": "ES2022", + "moduleResolution": "bundler", "resolveJsonModule": true, "emitDeclarationOnly": true, "sourceMap": false, diff --git a/packages/rspack/tsconfig.json b/packages/rspack/tsconfig.json index 12626bc91629..09a74d6bb78b 100644 --- a/packages/rspack/tsconfig.json +++ b/packages/rspack/tsconfig.json @@ -3,6 +3,8 @@ "compilerOptions": { "outDir": "dist", "rootDir": "src", + "module": "ES2022", + "moduleResolution": "bundler", "lib": ["es2022", "dom"], "emitDeclarationOnly": true, "paths": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a93a025dad53..bb005974d189 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -29,8 +29,8 @@ importers: specifier: workspace:* version: link:packages/rspack-cli '@rstest/core': - specifier: ^0.7.8 - version: 0.7.8(jsdom@26.1.0) + specifier: ^0.7.9 + version: 0.7.9(jsdom@26.1.0) '@taplo/cli': specifier: ^0.7.0 version: 0.7.0 @@ -639,6 +639,9 @@ importers: '@babel/preset-react': specifier: ^7.28.5 version: 7.28.5(@babel/core@7.28.5) + '@module-federation/runtime-tools': + specifier: ^0.22.0 + version: 0.22.0 '@playwright/test': specifier: 1.57.0 version: 1.57.0 @@ -730,8 +733,8 @@ importers: specifier: workspace:* version: link:../../packages/rspack-test-tools '@rstest/core': - specifier: ^0.7.8 - version: 0.7.8(jsdom@26.1.0) + specifier: ^0.7.9 + version: 0.7.9(jsdom@26.1.0) '@swc/helpers': specifier: 0.5.18 version: 0.5.18 @@ -3576,8 +3579,8 @@ packages: '@rstack-dev/doc-ui@1.12.2': resolution: {integrity: sha512-4C+tfhODxCp81ohCik9baOdbhYGNFqdwcwQMAESncF0YX3EawdNCORI1E26DqkY/F3ggfKG4qOlEAu+oOxrPxg==} - '@rstest/core@0.7.8': - resolution: {integrity: sha512-A7oN5GLMYuVkTGjXTH+69nz3wR0lxHUkWax+hVq+jNQmcf81ZqJosTLqN6jwFZdmCfHbj3iTd9ku6boo8tJlnA==} + '@rstest/core@0.7.9': + resolution: {integrity: sha512-RHNPS1MDUxtf+1Z0YZi+vIQ13SdvCbcbpzDA7XHcPziTRy2mAPg8nfcms+XzbIp95KXH75ucAhgAKNFO0QgARA==} engines: {node: '>=18.12.0'} hasBin: true peerDependencies: @@ -11141,7 +11144,7 @@ snapshots: - react - react-dom - '@rstest/core@0.7.8(jsdom@26.1.0)': + '@rstest/core@0.7.9(jsdom@26.1.0)': dependencies: '@rsbuild/core': 1.7.1 '@types/chai': 5.2.3 diff --git a/tests/e2e/cases/chunk/esm_split/src/index.js b/tests/e2e/cases/chunk/esm_split/src/index.js index 639af601baeb..91d4f507b748 100644 --- a/tests/e2e/cases/chunk/esm_split/src/index.js +++ b/tests/e2e/cases/chunk/esm_split/src/index.js @@ -1,3 +1,3 @@ -import { text } from './split'; +import { text } from './split.js'; document.getElementById('root').innerText = text; diff --git a/tests/e2e/cases/chunk/issue-4936/index.test.ts b/tests/e2e/cases/chunk/issue-4936/index.test.ts index 60feaad3b111..9d307ebc4826 100644 --- a/tests/e2e/cases/chunk/issue-4936/index.test.ts +++ b/tests/e2e/cases/chunk/issue-4936/index.test.ts @@ -7,7 +7,7 @@ test('should load success', async ({ page, fileAction }) => { fileAction.updateFile( './src/index.js', () => ` -import(/* webpackChunkName: "bar" */'./app').then((m) => { +import(/* webpackChunkName: "bar" */'./app.js').then((m) => { m.title('456') });`, ); diff --git a/tests/e2e/cases/chunk/issue-4936/src/index.js b/tests/e2e/cases/chunk/issue-4936/src/index.js index f7f2e607a634..6ce15db775a0 100644 --- a/tests/e2e/cases/chunk/issue-4936/src/index.js +++ b/tests/e2e/cases/chunk/issue-4936/src/index.js @@ -1,3 +1,3 @@ -import('./app').then((m) => { +import('./app.js').then((m) => { m.title('123'); }); diff --git a/tests/e2e/cases/css/chunk-loading-order/src/index.js b/tests/e2e/cases/css/chunk-loading-order/src/index.js index bdaa919fbc16..08d893d53134 100644 --- a/tests/e2e/cases/css/chunk-loading-order/src/index.js +++ b/tests/e2e/cases/css/chunk-loading-order/src/index.js @@ -1,4 +1,4 @@ -import('./async').then(() => { +import('./async.js').then(() => { const div = document.createElement('div'); div.innerText = 'ok'; div.id = 'status'; diff --git a/tests/e2e/cases/css/import-empty-css-file/src/index.js b/tests/e2e/cases/css/import-empty-css-file/src/index.js index 5a4eda2ed856..3782435bd797 100644 --- a/tests/e2e/cases/css/import-empty-css-file/src/index.js +++ b/tests/e2e/cases/css/import-empty-css-file/src/index.js @@ -1,3 +1,3 @@ -import('./empty').then(() => { +import('./empty.js').then(() => { document.getElementById('root').innerText = 'ok'; }); diff --git a/tests/e2e/cases/file/context-delete-file/src/index.js b/tests/e2e/cases/file/context-delete-file/src/index.js index 98c3fd6e4605..5c5a8f124be2 100644 --- a/tests/e2e/cases/file/context-delete-file/src/index.js +++ b/tests/e2e/cases/file/context-delete-file/src/index.js @@ -4,9 +4,9 @@ console.log(context); document.getElementById('root').textContent = '__PAGE_RENDER__'; -if (module.hot) { - module.hot.accept(); - module.hot.addStatusHandler((status) => { +if (import.meta.webpackHot) { + import.meta.webpackHot.accept(); + import.meta.webpackHot.addStatusHandler((status) => { if (status === 'idle') { document.getElementById('root').textContent = '__HMR_UPDATED__'; } diff --git a/tests/e2e/cases/file/missing-files/index.test.ts b/tests/e2e/cases/file/missing-files/index.test.ts index 6584ce8be783..b6d885119b96 100644 --- a/tests/e2e/cases/file/missing-files/index.test.ts +++ b/tests/e2e/cases/file/missing-files/index.test.ts @@ -6,10 +6,10 @@ test('missing files should be able to recover if being added back', async ({ }) => { const overlay = page.frameLocator('#webpack-dev-server-client-overlay'); await expect( - overlay.getByText("Can't resolve './missing-file-1'"), + overlay.getByText("Can't resolve './missing-file-1.js'"), ).toBeVisible(); await expect( - overlay.getByText("Can't resolve './missing-file-2'"), + overlay.getByText("Can't resolve './missing-file-2.js'"), ).toBeVisible(); fileAction.updateFile( @@ -28,7 +28,7 @@ test('missing files should be able to recover if being added back', async ({ fileAction.deleteFile('src/missing-file-1.js'); await expect( - overlay.getByText("Can't resolve './missing-file-1'"), + overlay.getByText("Can't resolve './missing-file-1.js'"), ).toBeVisible(); fileAction.updateFile( diff --git a/tests/e2e/cases/file/missing-files/src/index.js b/tests/e2e/cases/file/missing-files/src/index.js index e7751e12c453..23529e6671d0 100644 --- a/tests/e2e/cases/file/missing-files/src/index.js +++ b/tests/e2e/cases/file/missing-files/src/index.js @@ -1,6 +1,6 @@ // @ts-nocheck -import { a } from './missing-file-1'; -const { b } = require('./missing-file-2'); +import { a } from './missing-file-1.js'; +import { b } from './missing-file-2.js'; document.getElementById('root').innerHTML = ` ${a} diff --git a/tests/e2e/cases/hooks/asset-emitted/src/index.js b/tests/e2e/cases/hooks/asset-emitted/src/index.js index 0183d9a8405e..58c8be51dc9a 100644 --- a/tests/e2e/cases/hooks/asset-emitted/src/index.js +++ b/tests/e2e/cases/hooks/asset-emitted/src/index.js @@ -1,3 +1,3 @@ -import('./foo').then((m) => { +import('./foo.js').then((m) => { document.getElementById('root').innerText = `__ROOT_TEXT__${m.foo}`; }); diff --git a/tests/e2e/cases/incremental/remove-optimized-module/comp/index.js b/tests/e2e/cases/incremental/remove-optimized-module/comp/index.js index fe9c53c5118c..cc0b3103ad90 100644 --- a/tests/e2e/cases/incremental/remove-optimized-module/comp/index.js +++ b/tests/e2e/cases/incremental/remove-optimized-module/comp/index.js @@ -1 +1 @@ -export { Button } from './Button'; +export { Button } from './Button.js'; diff --git a/tests/e2e/cases/incremental/remove-optimized-module/index.js b/tests/e2e/cases/incremental/remove-optimized-module/index.js index 166a45729a70..d0e50a1a313a 100644 --- a/tests/e2e/cases/incremental/remove-optimized-module/index.js +++ b/tests/e2e/cases/incremental/remove-optimized-module/index.js @@ -1,4 +1,4 @@ -import { Button } from './comp'; +import { Button } from './comp/index.js'; const div = document.createElement('div'); div.id = 'main'; diff --git a/tests/e2e/cases/incremental/remove-optimized-module/index.test.ts b/tests/e2e/cases/incremental/remove-optimized-module/index.test.ts index 4afc3d4ffcbb..1166e05adc5a 100644 --- a/tests/e2e/cases/incremental/remove-optimized-module/index.test.ts +++ b/tests/e2e/cases/incremental/remove-optimized-module/index.test.ts @@ -10,7 +10,7 @@ test('remove optimized module should not panic', async ({ const overlay = page.frameLocator('#webpack-dev-server-client-overlay'); await expect( - overlay.getByText("Module not found: Can't resolve './Button'"), + overlay.getByText("Module not found: Can't resolve './Button.js'"), ).toBeVisible(); fileAction.updateFile( diff --git a/tests/e2e/cases/incremental/remove-optimized-module/package.json b/tests/e2e/cases/incremental/remove-optimized-module/package.json index 490b04c2f074..d9d896f180e5 100644 --- a/tests/e2e/cases/incremental/remove-optimized-module/package.json +++ b/tests/e2e/cases/incremental/remove-optimized-module/package.json @@ -1,4 +1,5 @@ { "name": "test", + "type": "module", "sideEffects": false } diff --git a/tests/e2e/cases/lazy-compilation/module-federation/runtime-plugin.js b/tests/e2e/cases/lazy-compilation/module-federation/runtime-plugin.js index d8d157f9cb72..a86f7daf0a6d 100644 --- a/tests/e2e/cases/lazy-compilation/module-federation/runtime-plugin.js +++ b/tests/e2e/cases/lazy-compilation/module-federation/runtime-plugin.js @@ -1,4 +1,4 @@ -module.exports = function () { +export default function () { let component; return { name: 'proxy-remote', @@ -12,4 +12,4 @@ module.exports = function () { return () => component; }, }; -}; +} diff --git a/tests/e2e/cases/lazy-compilation/persistent-cache/src/index.js b/tests/e2e/cases/lazy-compilation/persistent-cache/src/index.js index 51908fe0157d..bf65053dae63 100644 --- a/tests/e2e/cases/lazy-compilation/persistent-cache/src/index.js +++ b/tests/e2e/cases/lazy-compilation/persistent-cache/src/index.js @@ -4,5 +4,5 @@ button.id = 'click_button'; document.body.appendChild(button); button.addEventListener('click', async () => { - import('./dyn'); + import('./dyn.js'); }); diff --git a/tests/e2e/cases/make/failed_module_by_js_loader/loader.js b/tests/e2e/cases/make/failed_module_by_js_loader/loader.cjs similarity index 100% rename from tests/e2e/cases/make/failed_module_by_js_loader/loader.js rename to tests/e2e/cases/make/failed_module_by_js_loader/loader.cjs diff --git a/tests/e2e/cases/make/failed_module_by_js_loader/rspack.config.js b/tests/e2e/cases/make/failed_module_by_js_loader/rspack.config.js index b973a428928c..7e106636eb5c 100644 --- a/tests/e2e/cases/make/failed_module_by_js_loader/rspack.config.js +++ b/tests/e2e/cases/make/failed_module_by_js_loader/rspack.config.js @@ -12,7 +12,7 @@ module.exports = { test: /\.js$/, exclude: [/node_modules/], include: [/src/], - loader: './loader.js', + loader: './loader.cjs', }, ], }, diff --git a/tests/e2e/cases/make/remove-dynamic-entry-with-loader/loader.js b/tests/e2e/cases/make/remove-dynamic-entry-with-loader/loader.js index 607b15bc4643..3ce45198a75a 100644 --- a/tests/e2e/cases/make/remove-dynamic-entry-with-loader/loader.js +++ b/tests/e2e/cases/make/remove-dynamic-entry-with-loader/loader.js @@ -1,4 +1,7 @@ -// @ts-nocheck -module.exports = function () { - return `require(${JSON.stringify(this.resourcePath)})`; -}; +export default function () { + const path = JSON.stringify(this.resourcePath); + + return ` + export * from ${path}; + `; +} diff --git a/tests/e2e/cases/make/rewrite-factorize-request/index.js b/tests/e2e/cases/make/rewrite-factorize-request/index.js index 9c46f33ce5cf..fd249e1b5e59 100644 --- a/tests/e2e/cases/make/rewrite-factorize-request/index.js +++ b/tests/e2e/cases/make/rewrite-factorize-request/index.js @@ -1,4 +1,4 @@ -import num from './file'; +import num from './file.js'; const div = document.createElement('div'); div.innerText = String(num); diff --git a/tests/e2e/cases/make/rewrite-factorize-request/loader.js b/tests/e2e/cases/make/rewrite-factorize-request/loader.cjs similarity index 100% rename from tests/e2e/cases/make/rewrite-factorize-request/loader.js rename to tests/e2e/cases/make/rewrite-factorize-request/loader.cjs diff --git a/tests/e2e/cases/make/rewrite-factorize-request/rspack.config.js b/tests/e2e/cases/make/rewrite-factorize-request/rspack.config.js index fa9df7b72fc5..d1c0e0098a3b 100644 --- a/tests/e2e/cases/make/rewrite-factorize-request/rspack.config.js +++ b/tests/e2e/cases/make/rewrite-factorize-request/rspack.config.js @@ -24,8 +24,8 @@ module.exports = { normalModuleFactory.hooks.resolve.tapPromise( 'PLUGIN', async (resolveData) => { - if (resolveData.request == './file') { - resolveData.request = `./loader.js?time=${sharedObj.time}!./file`; + if (resolveData.request == './file.js') { + resolveData.request = `./loader.cjs?time=${sharedObj.time}!./file.js`; } }, ); diff --git a/tests/e2e/cases/persistent-cache/rename-file/index.js b/tests/e2e/cases/persistent-cache/rename-file/index.js index 7fb845482cc2..13793a5de950 100644 --- a/tests/e2e/cases/persistent-cache/rename-file/index.js +++ b/tests/e2e/cases/persistent-cache/rename-file/index.js @@ -1,5 +1,5 @@ -import a from './a'; -import b from './b'; +import a from './a.js'; +import b from './b.js'; const div = document.createElement('div'); div.innerText = a + b; diff --git a/tests/e2e/cases/worker/worker-hmr/src/worker.js b/tests/e2e/cases/worker/worker-hmr/src/worker.js index df7f43234525..756e326f2b21 100644 --- a/tests/e2e/cases/worker/worker-hmr/src/worker.js +++ b/tests/e2e/cases/worker/worker-hmr/src/worker.js @@ -1,3 +1,3 @@ self.postMessage('__PLACEHOLDER__'); -module.hot.accept(); +import.meta.webpackHot.accept(); diff --git a/tests/e2e/fixtures/pathInfo.ts b/tests/e2e/fixtures/pathInfo.ts index 5b3f4649a633..442e2dee076c 100644 --- a/tests/e2e/fixtures/pathInfo.ts +++ b/tests/e2e/fixtures/pathInfo.ts @@ -1,6 +1,9 @@ import path from 'node:path'; import fs from 'fs-extra'; import type { Fixtures } from '@playwright/test'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); type PathInfo = { testFile: string; @@ -12,7 +15,7 @@ export type PathInfoFixtures = { pathInfo: PathInfo; }; -const tempDir = path.resolve(__dirname, '../temp'); +const tempDir = path.resolve(import.meta.dirname, '../temp'); async function calcPathInfo( testFile: string, workerId: string, diff --git a/tests/e2e/fixtures/rspack.ts b/tests/e2e/fixtures/rspack.ts index 0aea6f2c2dc1..9578f8389c3c 100644 --- a/tests/e2e/fixtures/rspack.ts +++ b/tests/e2e/fixtures/rspack.ts @@ -8,6 +8,9 @@ import { } from '@rspack/core'; import { RspackDevServer } from '@rspack/dev-server'; import type { PathInfoFixtures } from './pathInfo'; +import { createRequire } from 'node:module'; + +const require = createRequire(import.meta.url); class Rspack { private config: RspackConfig; diff --git a/tests/e2e/package.json b/tests/e2e/package.json index e9de9b489e9b..363f14f4c967 100644 --- a/tests/e2e/package.json +++ b/tests/e2e/package.json @@ -2,8 +2,9 @@ "name": "e2e-test", "private": true, "version": "0.1.8", + "type": "module", "scripts": { - "test": "playwright test", + "test": "PW_EXPERIMENTAL_TS_ESM=1 playwright test", "test:CI": "CI=1 pnpm run test" }, "devDependencies": { @@ -14,6 +15,7 @@ "@rspack/core": "workspace:*", "@rspack/dev-server": "~1.1.5", "@rspack/plugin-react-refresh": "^1.6.0", + "@module-federation/runtime-tools": "^0.22.0", "@swc/helpers": "0.5.18", "@types/fs-extra": "11.0.4", "babel-loader": "^10.0.0", diff --git a/tests/e2e/tsconfig.json b/tests/e2e/tsconfig.json index f08a76f1ce7f..2727cbc0f0cf 100644 --- a/tests/e2e/tsconfig.json +++ b/tests/e2e/tsconfig.json @@ -4,6 +4,8 @@ "compilerOptions": { "strict": true, "baseUrl": ".", + "module": "ES2022", + "moduleResolution": "bundler", "paths": { "@/*": ["./*"] }, diff --git a/tests/rspack-test/errorCases/error-read.js b/tests/rspack-test/errorCases/error-read.js index e701dd8e7eef..6d928a232c0c 100644 --- a/tests/rspack-test/errorCases/error-read.js +++ b/tests/rspack-test/errorCases/error-read.js @@ -135,7 +135,7 @@ module.exports = [ "index": 1, "message": " × ", "name": "Error", - "stack": "Error: at /errorCases/error-read.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: at /errorCases/error-read.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ] `); diff --git a/tests/rspack-test/errorCases/error-write.js b/tests/rspack-test/errorCases/error-write.js index b31ae4372132..8d7342dc6bb3 100644 --- a/tests/rspack-test/errorCases/error-write.js +++ b/tests/rspack-test/errorCases/error-write.js @@ -46,7 +46,7 @@ module.exports = [ "code": "Error", "message": " × test push", "moduleTrace": Array [], - "stack": "Error: test push at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test push at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, Object { "code": "Error", @@ -93,7 +93,7 @@ module.exports = [ "code": "Error", "message": " × error 1", "moduleTrace": Array [], - "stack": "Error: error 1 at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: error 1 at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], "warnings": Array [], @@ -123,13 +123,13 @@ module.exports = [ "code": "Error", "message": " × error 1", "moduleTrace": Array [], - "stack": "Error: error 1 at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: error 1 at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, Object { "code": "Error", "message": " × error 2", "moduleTrace": Array [], - "stack": "Error: error 2 at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: error 2 at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], "warnings": Array [], @@ -163,7 +163,7 @@ module.exports = [ "code": "Error", "message": " × test unshift", "moduleTrace": Array [], - "stack": "Error: test unshift at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test unshift at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], "warnings": Array [], @@ -193,7 +193,7 @@ module.exports = [ "code": "Error", "message": " × test splice", "moduleTrace": Array [], - "stack": "Error: test splice at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test splice at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], "warnings": Array [], @@ -223,7 +223,7 @@ module.exports = [ "code": "Error", "message": " × test splice", "moduleTrace": Array [], - "stack": "Error: test splice at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test splice at /errorCases/error-write.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, Object { "loc": "1:1-33", diff --git a/tests/rspack-test/errorCases/warning-modify.js b/tests/rspack-test/errorCases/warning-modify.js index f1c3391bc98c..5a110d567547 100644 --- a/tests/rspack-test/errorCases/warning-modify.js +++ b/tests/rspack-test/errorCases/warning-modify.js @@ -46,7 +46,7 @@ module.exports = [ "code": "Error", "message": " ⚠ test push", "moduleTrace": Array [], - "stack": "Error: test push at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test push at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, Object { "code": "ModuleParseWarning", @@ -88,13 +88,13 @@ module.exports = [ "code": "Error", "message": " ⚠ warning 1", "moduleTrace": Array [], - "stack": "Error: warning 1 at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: warning 1 at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, Object { "code": "Error", "message": " ⚠ warning 2", "moduleTrace": Array [], - "stack": "Error: warning 2 at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: warning 2 at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], } @@ -128,7 +128,7 @@ module.exports = [ "code": "Error", "message": " ⚠ test unshift", "moduleTrace": Array [], - "stack": "Error: test unshift at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test unshift at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], } @@ -158,7 +158,7 @@ module.exports = [ "code": "Error", "message": " ⚠ test splice", "moduleTrace": Array [], - "stack": "Error: test splice at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test splice at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, ], } @@ -188,7 +188,7 @@ module.exports = [ "code": "Error", "message": " ⚠ test splice", "moduleTrace": Array [], - "stack": "Error: test splice at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.cjs) at /dist/index.js", + "stack": "Error: test splice at /errorCases/warning-modify.js at Object.fn (/dist/index.js) at next (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) at AsyncSeriesHook.callAsync (/node_modules//@rspack/lite-tapable/dist/index.js) at /dist/index.js", }, Object { "code": "ModuleParseWarning", diff --git a/tests/rspack-test/hotCases/css/recovery/__snapshots__/web/2.snap.txt b/tests/rspack-test/hotCases/css/recovery/__snapshots__/web/2.snap.txt index 6607845577a9..b124c6a85c58 100644 --- a/tests/rspack-test/hotCases/css/recovery/__snapshots__/web/2.snap.txt +++ b/tests/rspack-test/hotCases/css/recovery/__snapshots__/web/2.snap.txt @@ -6,7 +6,7 @@ ## Asset Files - Bundle: bundle.js - Manifest: main.LAST_HASH.hot-update.json, size: 28 -- Update: main.hot-update.js, size: 6674 +- Update: main.hot-update.js, size: 6025 ## Manifest @@ -27,28 +27,46 @@ - ./index.css #### Changed Runtime Modules +- webpack/runtime/define_property_getters - webpack/runtime/get_full_hash #### Changed Content ```js "use strict"; self["webpackHotUpdate"]("main", { -"../../../../../../../../packages/rspack/dist/cssExtractHmr.js"(__unused_rspack_module, exports) { +"./index.css"(module, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +// extracted by css-extract-rspack-plugin -var __nested_rspack_require_18_37__ = {}; -__nested_rspack_require_18_37__.d = (exports1, definition)=>{ - for(var key in definition)__nested_rspack_require_18_37__.o(definition, key) && !__nested_rspack_require_18_37__.o(exports1, key) && Object.defineProperty(exports1, key, { - enumerable: !0, - get: definition[key] - }); -}, __nested_rspack_require_18_37__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop), __nested_rspack_require_18_37__.r = (exports1)=>{ - "u" > typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports1, Symbol.toStringTag, { - value: 'Module' - }), Object.defineProperty(exports1, '__esModule', { - value: !0 - }); -}; -var __nested_rspack_exports__ = {}; + if(true) { + (function() { + var localsJsonString = undefined; + var cssReload = (__webpack_require__("../../../../../../../../packages/rspack/dist/cssExtractHmr.js")/* .cssReload */.cssReload)(module.id, {}); + // only invalidate when locals change + if ( + module.hot.data && + module.hot.data.value && + module.hot.data.value !== localsJsonString + ) { + module.hot.invalidate(); + } else { + module.hot.accept(); + } + module.hot.dispose(function(data) { + data.value = localsJsonString; + cssReload(); + }); + })(); + } + + +}, +"../../../../../../../../packages/rspack/dist/cssExtractHmr.js"(__unused_rspack___webpack_module__, __webpack_exports__, __webpack_require__) { +__webpack_require__.r(__webpack_exports__); +__webpack_require__.d(__webpack_exports__, { + cssReload: () => (cssReload), + normalizeUrl: () => (normalizeUrl) +}); function normalizeUrl(url) { let urlString = url.trim(); if (/^data:/i.test(urlString)) return urlString; @@ -66,11 +84,7 @@ function normalizeUrl(url) { return accumulator; }, []).join('/'); } -__nested_rspack_require_18_37__.r(__nested_rspack_exports__), __nested_rspack_require_18_37__.d(__nested_rspack_exports__, { - cssReload: ()=>cssReload, - normalizeUrl: ()=>normalizeUrl -}); -const srcByModuleId = Object.create(null), noDocument = "u" < typeof document, { forEach } = Array.prototype; +let srcByModuleId = Object.create(null), noDocument = "u" < typeof document, { forEach: forEach } = Array.prototype; function noop() {} function updateCss(el, url) { let normalizedUrl; @@ -151,45 +165,24 @@ function cssReload(moduleId, options) { }, 50); }; } -for(var __rspack_i in exports.cssReload = __nested_rspack_exports__.cssReload, exports.normalizeUrl = __nested_rspack_exports__.normalizeUrl, __nested_rspack_exports__)-1 === [ - "cssReload", - "normalizeUrl" -].indexOf(__rspack_i) && (exports[__rspack_i] = __nested_rspack_exports__[__rspack_i]); -Object.defineProperty(exports, "__esModule", ({ - value: !0 -})); - -}, -"./index.css"(module, __webpack_exports__, __webpack_require__) { -__webpack_require__.r(__webpack_exports__); -// extracted by css-extract-rspack-plugin - if(true) { - (function() { - var localsJsonString = undefined; - var cssReload = (__webpack_require__("../../../../../../../../packages/rspack/dist/cssExtractHmr.js")/* .cssReload */.cssReload)(module.id, {}); - // only invalidate when locals change - if ( - module.hot.data && - module.hot.data.value && - module.hot.data.value !== localsJsonString - ) { - module.hot.invalidate(); - } else { - module.hot.accept(); - } - module.hot.dispose(function(data) { - data.value = localsJsonString; - cssReload(); - }); - })(); - } - }, },function(__webpack_require__) { +// webpack/runtime/define_property_getters +(() => { + + __webpack_require__.d = function (exports, definition) { + for (var key in definition) { + if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { configurable: true, enumerable: true, get: definition[key] }); + } + } + }; + +})(); // webpack/runtime/get_full_hash (() => { __webpack_require__.h = () => ("CURRENT_HASH") diff --git a/tests/rspack-test/multiCompilerCases/pressure.js b/tests/rspack-test/multiCompilerCases/pressure.js index 2c6e57b2af10..bff286fbd3f9 100644 --- a/tests/rspack-test/multiCompilerCases/pressure.js +++ b/tests/rspack-test/multiCompilerCases/pressure.js @@ -1,4 +1,4 @@ -const rspack = require("@rspack/core"); +const { rspack } = require("@rspack/core"); const path = require("path"); const total = 100; const runnings = []; diff --git a/tests/rspack-test/package.json b/tests/rspack-test/package.json index 223daed57d12..9ce1e2178369 100644 --- a/tests/rspack-test/package.json +++ b/tests/rspack-test/package.json @@ -22,7 +22,7 @@ "@rspack/plugin-preact-refresh": "1.1.4", "@rspack/plugin-react-refresh": "^1.6.0", "@rspack/test-tools": "workspace:*", - "@rstest/core": "^0.7.8", + "@rstest/core": "^0.7.9", "@swc/helpers": "0.5.18", "@swc/plugin-remove-console": "^12.1.0", "@types/babel__generator": "7.27.0", diff --git a/tests/rspack-test/statsOutputCases/logging/__snapshots__/stats.txt b/tests/rspack-test/statsOutputCases/logging/__snapshots__/stats.txt index dc544d347102..a2a269ae8c2f 100644 --- a/tests/rspack-test/statsOutputCases/logging/__snapshots__/stats.txt +++ b/tests/rspack-test/statsOutputCases/logging/__snapshots__/stats.txt @@ -19,9 +19,9 @@ LOG from LogOtherTestPlugin LOG from /statsOutputCases/logging/index.js An error | at Object.fn (/dist/index.js) -| at SyncBailHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) -| at SyncBailHook.callStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) -| at SyncBailHook.call (/node_modules//@rspack/lite-tapable/dist/index.cjs) +| at SyncBailHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) +| at SyncBailHook.callStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) +| at SyncBailHook.call (/node_modules//@rspack/lite-tapable/dist/index.js) | at /dist/index.js | at StatsFactory._forEachLevel (/dist/index.js) | at StatsFactory._create (/dist/index.js) @@ -39,9 +39,9 @@ LOG from /statsOutputCases/logging/index.js | at onMessage (/node_modules//tinypool/dist/entry/process.js) A warning | at Object.fn (/dist/index.js) -| at SyncBailHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) -| at SyncBailHook.callStageRange (/node_modules//@rspack/lite-tapable/dist/index.cjs) -| at SyncBailHook.call (/node_modules//@rspack/lite-tapable/dist/index.cjs) +| at SyncBailHook.callAsyncStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) +| at SyncBailHook.callStageRange (/node_modules//@rspack/lite-tapable/dist/index.js) +| at SyncBailHook.call (/node_modules//@rspack/lite-tapable/dist/index.js) | at /dist/index.js | at StatsFactory._forEachLevel (/dist/index.js) | at StatsFactory._create (/dist/index.js) diff --git a/website/docs/en/guide/start/quick-start.mdx b/website/docs/en/guide/start/quick-start.mdx index 4fc79c762f3b..22f76a4c3d69 100644 --- a/website/docs/en/guide/start/quick-start.mdx +++ b/website/docs/en/guide/start/quick-start.mdx @@ -27,6 +27,7 @@ You can refer to the following installation guides and choose one runtime: Rspack has the following Node.js version requirements: +- `@rspack/cli >= v2.0.0` requires Node.js 20.19.0 or higher. - `@rspack/cli >= v1.0.0` requires Node.js 18.12.0 or higher. - `@rspack/core >= v1.5.0` requires Node.js 18.12.0 or higher. - `@rspack/core < v1.5.0` requires Node.js 16.0.0 or higher. diff --git a/website/docs/zh/guide/start/quick-start.mdx b/website/docs/zh/guide/start/quick-start.mdx index da800927471c..74fb0263e935 100644 --- a/website/docs/zh/guide/start/quick-start.mdx +++ b/website/docs/zh/guide/start/quick-start.mdx @@ -27,6 +27,7 @@ Rspack 支持使用 [Node.js](https://nodejs.org/)、[Deno](https://deno.com/) Rspack 对于 Node.js 的版本要求如下: +- `@rspack/cli >= v2.0.0` 要求 Node.js 20.19.0 或更高版本。 - `@rspack/cli >= v1.0.0` 要求 Node.js 18.12.0 或更高版本。 - `@rspack/core >= v1.5.0` 要求 Node.js 18.12.0 或更高版本。 - `@rspack/core < v1.5.0` 要求 Node.js 16.0.0 或更高版本。