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/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-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.ts similarity index 52% rename from packages/rspack-cli/rslib.config.mts rename to packages/rspack-cli/rslib.config.ts index aaf1419a3dba..07c2abf99ac9 100644 --- a/packages/rspack-cli/rslib.config.mts +++ b/packages/rspack-cli/rslib.config.ts @@ -1,24 +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: ['es2023'], - dts: true, - }, { 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..0873dde68eb3 100644 --- a/packages/rspack-cli/rstest.config.ts +++ b/packages/rspack-cli/rstest.config.ts @@ -16,12 +16,12 @@ 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', }, output: { - externals: [/@rspack\/core/], + externals: [/@rspack\/core/, /api-wrapper/], }, env: { RUST_BACKTRACE: 'full', diff --git a/packages/rspack-cli/src/cli.ts b/packages/rspack-cli/src/cli.ts index 46c84890c6fb..6d6b5da98a77 100644 --- a/packages/rspack-cli/src/cli.ts +++ b/packages/rspack-cli/src/cli.ts @@ -10,6 +10,7 @@ import type { RspackPluginInstance, Stats, } from '@rspack/core'; +import { rspack } from '@rspack/core'; import cac, { type CAC } from 'cac'; import { createColors, isColorSupported } from 'picocolors'; import { BuildCommand } from './commands/build'; @@ -21,7 +22,6 @@ import type { CommonOptions, CommonOptionsForBuildAndServe, } from './utils/options'; -import { rspack } from './utils/rspackCore'; type Command = 'serve' | 'build'; diff --git a/packages/rspack-cli/src/commands/preview.ts b/packages/rspack-cli/src/commands/preview.ts index b9fb683113d2..cabfad5875e1 100644 --- a/packages/rspack-cli/src/commands/preview.ts +++ b/packages/rspack-cli/src/commands/preview.ts @@ -4,6 +4,7 @@ import type { MultiRspackOptions, RspackOptions, } from '@rspack/core'; +import { rspack } from '@rspack/core'; import type { RspackCLI } from '../cli'; import type { RspackCommand } from '../types'; import { @@ -12,7 +13,6 @@ import { normalizeCommonOptions, setDefaultNodeEnv, } from '../utils/options'; -import { rspack } from '../utils/rspackCore'; type PreviewOptions = CommonOptions & { port?: string; diff --git a/packages/rspack-cli/src/commands/serve.ts b/packages/rspack-cli/src/commands/serve.ts index 4b1cf0a00047..50b278694ebe 100644 --- a/packages/rspack-cli/src/commands/serve.ts +++ b/packages/rspack-cli/src/commands/serve.ts @@ -1,4 +1,5 @@ import type { Compiler, MultiRspackOptions } from '@rspack/core'; +import { rspack } from '@rspack/core'; import type { RspackDevServer as RspackDevServerType } from '@rspack/dev-server'; import type { RspackCLI } from '../cli'; import { DEFAULT_SERVER_HOT } from '../constants'; @@ -10,7 +11,6 @@ import { normalizeCommonOptions, setDefaultNodeEnv, } from '../utils/options'; -import { rspack } from '../utils/rspackCore'; type ServerOptions = CommonOptionsForBuildAndServe & { hot?: boolean | 'only'; 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..72276d373a53 100644 --- a/packages/rspack-cli/src/utils/loadConfig.ts +++ b/packages/rspack-cli/src/utils/loadConfig.ts @@ -1,13 +1,16 @@ import fs from 'node:fs'; +import { createRequire } from 'node:module'; import path from 'node:path'; import type { MultiRspackOptions, RspackOptions } from '@rspack/core'; +import { rspack } from '@rspack/core'; import { addHook } from 'pirates'; import { crossImport } from './crossImport'; import findConfig from './findConfig'; import { isEsmFile } from './isEsmFile'; import isTsFile, { TS_EXTENSION } from './isTsFile'; import type { CommonOptions } from './options'; -import { rspack } from './rspackCore'; + +const require = createRequire(import.meta.url); const injectInlineSourceMap = ({ code, diff --git a/packages/rspack-cli/src/utils/profile.ts b/packages/rspack-cli/src/utils/profile.ts index ad34e9c202f3..ee736c91528e 100644 --- a/packages/rspack-cli/src/utils/profile.ts +++ b/packages/rspack-cli/src/utils/profile.ts @@ -5,7 +5,7 @@ */ import fs from 'node:fs'; import path from 'node:path'; -import { rspack } from './rspackCore'; +import { rspack } from '@rspack/core'; const DEFAULT_RUST_TRACE_LAYER = 'perfetto'; diff --git a/packages/rspack-cli/src/utils/rspackCore.ts b/packages/rspack-cli/src/utils/rspackCore.ts deleted file mode 100644 index 33dbaa7e95a8..000000000000 --- a/packages/rspack-cli/src/utils/rspackCore.ts +++ /dev/null @@ -1,12 +0,0 @@ -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 }; diff --git a/packages/rspack-cli/tests/api/type/api-wrapper.cjs b/packages/rspack-cli/tests/api/type/api-wrapper.cjs new file mode 100644 index 000000000000..c86fd31a7266 --- /dev/null +++ b/packages/rspack-cli/tests/api/type/api-wrapper.cjs @@ -0,0 +1,11 @@ +const rspackCjsDefaultRequire = require('@rspack/core'); +const { + rspack: rspackCjsNamedRequire, + webpack: webpackCjsNamedRequire, +} = require('@rspack/core'); + +module.exports = { + rspackCjsDefaultRequire, + rspackCjsNamedRequire, + webpackCjsNamedRequire, +}; diff --git a/packages/rspack-cli/tests/api/type/api-wrapper.mjs b/packages/rspack-cli/tests/api/type/api-wrapper.mjs new file mode 100644 index 000000000000..0edc0096f078 --- /dev/null +++ b/packages/rspack-cli/tests/api/type/api-wrapper.mjs @@ -0,0 +1,7 @@ +import rspackEsmDefaultImport, { + rspack as rspackEsmNamedImport, +} from '@rspack/core'; + +import * as rspackNamespaceImport from '@rspack/core'; + +export { rspackEsmDefaultImport, rspackEsmNamedImport, rspackNamespaceImport }; 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..c6ad551b43c6 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 @@ -1,36 +1,36 @@ -const rspackCjsDefaultRequire = require('@rspack/core'); -const { rspack: rspackCjsNamedRequire } = require('@rspack/core'); - import assert from 'node:assert'; - -type IsFunction = T extends (...args: any[]) => any ? true : false; +const { + rspackCjsDefaultRequire, + rspackCjsNamedRequire, + webpackCjsNamedRequire, +} = require('./api-wrapper.cjs'); // 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 () => { - type Truthy = IsFunction; - const truthy: Truthy = true; - truthy; - assert(rspackCjsDefaultRequire.BannerPlugin); + // const rspack = require('@rspack/core') assert(typeof rspackCjsDefaultRequire === 'function'); + assert(rspackCjsDefaultRequire.BannerPlugin); const compiler = rspackCjsDefaultRequire({}); assert(compiler); }); it('cjs named require', async () => { - type Truthy = IsFunction; - const truthy: Truthy = true; - truthy; - assert(rspackCjsNamedRequire.BannerPlugin); + // const { rspack } = require('@rspack/core') assert(typeof rspackCjsNamedRequire === 'function'); + // const { webpack } = require('@rspack/core') + assert(typeof webpackCjsNamedRequire === 'function'); + assert(rspackCjsNamedRequire.BannerPlugin); const compiler = rspackCjsNamedRequire({}); assert(compiler); }); it('rspack.default should not exist in cjs require', async () => { + // const { rspack } = require('@rspack/core') assert(!(rspackCjsNamedRequire as any).default); + // const rspack = require('@rspack/core') 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.mts deleted file mode 100644 index 34651d84d6ee..000000000000 --- a/packages/rspack-cli/tests/api/type/js-api-esm.test.mts +++ /dev/null @@ -1,35 +0,0 @@ -import assert from 'node:assert'; -import rspackEsmDefaultImport, { - rspack as rspackEsmNamedImport, -} from '@rspack/core'; - -type IsFunction = T extends (...args: any[]) => any ? true : false; - -// 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.BannerPlugin); - }); - - it('esm named import', async () => { - type Truthy = IsFunction; - const truthy: Truthy = true; - truthy; - assert(rspackEsmNamedImport.BannerPlugin); - assert(typeof rspackEsmNamedImport === 'function'); - const compiler = rspackEsmNamedImport({}); - assert(compiler); - }); - - it('rspack.default should not exist in esm import', async () => { - assert(!(rspackEsmNamedImport as any).default); - assert(!(rspackEsmDefaultImport as any).default); - }); - }, -); diff --git a/packages/rspack-cli/tests/api/type/js-api-esm.test.ts b/packages/rspack-cli/tests/api/type/js-api-esm.test.ts new file mode 100644 index 000000000000..8df973e95a7d --- /dev/null +++ b/packages/rspack-cli/tests/api/type/js-api-esm.test.ts @@ -0,0 +1,50 @@ +import assert from 'node:assert'; +import { + rspackEsmDefaultImport, + rspackEsmNamedImport, + rspackNamespaceImport, +} from './api-wrapper.mjs'; + +// 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 () => { + // import rspack from '@rspack/core' + assert(typeof rspackEsmDefaultImport === 'function'); + assert(rspackEsmDefaultImport.BannerPlugin); + const compiler = rspackEsmDefaultImport({}); + assert(compiler); + }); + + it('esm namespace import', async () => { + // import * as rspack from '@rspack/core' + assert(typeof rspackNamespaceImport === 'object'); + assert(typeof rspackNamespaceImport.rspack === 'function'); + assert(rspackNamespaceImport.BannerPlugin); + const compiler1 = rspackNamespaceImport.rspack({}); + assert(compiler1); + const compiler2 = rspackNamespaceImport.default({}); + assert(compiler2); + }); + + it('esm named import', async () => { + // import { rspack } from '@rspack/core' + assert(typeof rspackEsmNamedImport === 'function'); + assert(rspackEsmNamedImport.BannerPlugin); + const compiler = rspackEsmNamedImport({}); + assert(compiler); + }); + + it('rspack.default should not exist in esm named and default import', async () => { + assert(!(rspackEsmNamedImport as any).default); + assert(!(rspackEsmDefaultImport as any).default); + }); + + it('rspack.default should exist in esm namespace import', async () => { + assert((rspackNamespaceImport as any).default); + assert(typeof (rspackNamespaceImport as any).default === 'function'); + assert(rspackNamespaceImport.default === rspackNamespaceImport.rspack); + }); + }, +); 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 1999bd97f2d9..84ae8a0d6f1d 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); @@ -879,6 +946,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) @@ -1328,6 +1402,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) @@ -2851,6 +2958,15 @@ interface FunctionExpression extends Fn, ExpressionBase { type: "FunctionExpression"; } +// @public (undocumented) +interface GeneratedSourceInfo { + generatedColumn?: number; + + generatedLine?: number; + + source?: string; +} + // @public export type GeneratorOptionsByModuleType = GeneratorOptionsByModuleTypeKnown | GeneratorOptionsByModuleTypeUnknown; @@ -5330,12 +5446,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; @@ -5348,6 +5478,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; @@ -5513,6 +5650,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): { @@ -5844,6 +6007,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; @@ -6000,6 +6191,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; @@ -6250,6 +6467,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; @@ -7345,6 +7613,11 @@ export const sharing: { SharePlugin: typeof SharePlugin; }; +// @public (undocumented) +class SizeOnlySource extends Source { + constructor(size: number); +} + // @public (undocumented) export type SnapshotOptions = {}; @@ -7372,6 +7645,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): { @@ -7388,6 +7676,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) @@ -7718,6 +8075,16 @@ type StatSyncOptions = { throwIfNoEntry?: boolean; }; +// @public (undocumented) +interface StreamChunksOptions { + // (undocumented) + columns?: boolean; + // (undocumented) + finalSource?: boolean; + // (undocumented) + source?: boolean; +} + // @public (undocumented) interface StreamOptions { // (undocumented) @@ -9066,6 +9433,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..51d6f02412fb 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 { emitter as 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..9f5e5b5cded6 100644 --- a/packages/rspack/hot/emitter.js +++ b/packages/rspack/hot/emitter.js @@ -18,4 +18,8 @@ EventEmitter.prototype.emit = function (eventName) { } }; -module.exports = new EventEmitter(); +var emitter = new EventEmitter(); + +// TODO: remove default export when rspack-dev-server refactored +export default emitter; +export { emitter }; diff --git a/packages/rspack/hot/lazy-compilation-node.js b/packages/rspack/hot/lazy-compilation-node.js index 9ecf07ab958d..41411bb287cd 100644 --- a/packages/rspack/hot/lazy-compilation-node.js +++ b/packages/rspack/hot/lazy-compilation-node.js @@ -1,14 +1,16 @@ +import { createRequire } from 'node:module'; + var urlBase = decodeURIComponent(__resourceQuery.slice(1)); +var require = createRequire(import.meta.url); /** * @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 = ( @@ -22,7 +24,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..6c214e073132 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) { +function logApplyResult(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,6 @@ module.exports = function (updatedModules, renewedModules) { '[HMR] Consider using the optimization.moduleIds: "named" for module names.', ); } -}; +} + +export { logApplyResult }; diff --git a/packages/rspack/hot/log.js b/packages/rspack/hot/log.js index 2d409ed27c4d..40559bf46434 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,13 @@ module.exports.formatError = function (err) { return stack; } }; + +log.group = group; +log.groupCollapsed = groupCollapsed; +log.groupEnd = groupEnd; +log.setLogLevel = setLogLevel; +log.formatError = formatError; + +// TODO: remove default export when rspack-dev-server refactored +export default log; +export { log }; diff --git a/packages/rspack/hot/only-dev-server.js b/packages/rspack/hot/only-dev-server.js index 28b6f789ca6f..8e16997ee1bb 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 { emitter as 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..516217373888 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..322bb0afbb9c 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 8ebe802e28af..1e546c987661 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", diff --git a/packages/rspack/rslib.browser.config.mts b/packages/rspack/rslib.browser.config.mts index 0240c18795e6..fea60e400dfb 100644 --- a/packages/rspack/rslib.browser.config.mts +++ b/packages/rspack/rslib.browser.config.mts @@ -1,3 +1,4 @@ +// TODO: refactor pure ESM and verify browser behavior import fs from 'node:fs/promises'; import path from 'node:path'; import vm from 'node:vm'; @@ -220,6 +221,12 @@ async function getModuleFederationRuntimeCode() { const { code: downgradedRuntime } = await swc.transform(runtime, { jsc: { target: 'es2015', + parser: { + syntax: 'ecmascript', + }, + }, + module: { + type: 'commonjs', }, }); @@ -229,12 +236,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 55% rename from packages/rspack/rslib.config.mts rename to packages/rspack/rslib.config.ts index 5b2561b6fe04..b1840ea8d6e5 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,23 @@ const externalAlias: rsbuild.Rspack.Externals = ({ request }, callback) => { }; const commonLibConfig: LibConfig = { - format: 'cjs', + 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', + }, + '@rspack/binding/package.json', + externalAlias, + ], minify: { js: true, jsOptions: { @@ -55,14 +75,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 +101,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 +174,11 @@ export default defineConfig({ dts: { build: true, }, + redirect: { + dts: { + extension: true, + }, + }, source: { entry: { index: './src/index.ts', @@ -139,9 +188,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 +224,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 d80e38f818f2..cab36c83086c 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 dcadde1c69fd..d11d40ca5dfc 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/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..430070a2f521 100644 --- a/tests/e2e/package.json +++ b/tests/e2e/package.json @@ -2,6 +2,7 @@ "name": "e2e-test", "private": true, "version": "0.1.8", + "type": "module", "scripts": { "test": "playwright test", "test:CI": "CI=1 pnpm run test" @@ -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/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)