import type { AssetInfo, RawModuleRuleUse, RawOptions } from '@rspack/binding'; import type { Compilation } from '../Compilation.js'; import type { Compiler } from '../Compiler.js'; import { type LoaderObject } from '../loader-runner/index.js'; import type { Logger } from '../logging/Logger.js'; import type { Module } from '../Module.js'; import type { ResolveRequest } from '../Resolver.js'; import type Hash from '../util/hash/index.js'; import type { RspackOptionsNormalized } from './normalization.js'; import type { Mode, PublicPath, Resolve, RuleSetLoaderWithOptions, RuleSetUseItem, Target } from './types.js'; export declare const BUILTIN_LOADER_PREFIX = "builtin:"; export interface ComposeJsUseOptions { context: RawOptions['context']; mode: RawOptions['mode']; experiments: RawOptions['experiments']; compiler: Compiler; } export interface RawSourceMap { /** * The version of the source map format, always 3 */ version: number; /** * A list of original sources used by the mappings field */ sources: string[]; /** * A string with the encoded mapping data */ mappings: string; /** * The filename of the generated code that this source map is associated with */ file: string; /** * An optional source root string, used for relocating source files on a server * or removing repeated values in the sources entry. */ sourceRoot?: string; /** * An array containing the actual content of the original source files */ sourcesContent?: string[]; /** * A list of symbol names which may be used by the mappings field. */ names: string[]; /** * A unique identifier for debugging purposes */ debugId?: string; /** * An array of indices into the sources array, indicating which sources * should be ignored by debuggers */ ignoreList?: number[]; } export interface AdditionalData { [index: string]: any; } export type LoaderContextCallback = (err?: Error | null, content?: string | Buffer, sourceMap?: string | RawSourceMap, additionalData?: AdditionalData) => void; export type ErrorWithDetails = Error & { details?: string; }; export type ResolveCallback = (err: null | ErrorWithDetails, res?: string | false, req?: ResolveRequest) => void; export interface DiagnosticLocation { /** Text for highlighting the location */ text?: string; /** 1-based line */ line: number; /** 0-based column in bytes */ column: number; /** Length in bytes */ length: number; } export interface Diagnostic { message: string; help?: string; sourceCode?: string; /** * Location to the source code. * If `sourceCode` is not provided, location will be omitted. */ location?: DiagnosticLocation; /** * Optional filename to show. * If provided, it becomes the `StatsError.file` value in stats. */ file?: string; severity: 'error' | 'warning'; } export interface LoaderExperiments { emitDiagnostic(diagnostic: Diagnostic): void; } export interface ImportModuleOptions { /** * Specify a layer in which this module is placed/compiled */ layer?: string; /** * The public path used for the built modules */ publicPath?: PublicPath; /** * Target base uri */ baseUri?: string; } export interface LoaderContext { /** * The version number of the loader API. Currently 2. * This is useful for providing backwards compatibility. Using the version you can specify * custom logic or fallbacks for breaking changes. */ version: 2; /** * The path string of the current module. * @example `'/abc/resource.js?query#hash'`. */ resource: string; /** * The path string of the current module, excluding the query and fragment parameters. * @example `'/abc/resource.js?query#hash'` in `'/abc/resource.js'`. */ resourcePath: string; /** * The query parameter for the path string of the current module. * @example `'?query'` in `'/abc/resource.js?query#hash'`. */ resourceQuery: string; /** * The fragment parameter of the current module's path string. * @example `'#hash'` in `'/abc/resource.js?query#hash'`. */ resourceFragment: string; /** * Tells Rspack that this loader will be called asynchronously. Returns `this.callback`. */ async(): LoaderContextCallback; /** * A function that can be called synchronously or asynchronously in order to return multiple * results. The expected arguments are: * * 1. The first parameter must be `Error` or `null`, which marks the current module as a * compilation failure. * 2. The second argument is a `string` or `Buffer`, which indicates the contents of the file * after the module has been processed by the loader. * 3. The third parameter is a source map that can be processed by the loader. * 4. The fourth parameter is ignored by Rspack and can be anything (e.g. some metadata). */ callback: LoaderContextCallback; /** * A function that sets the cacheable flag. * By default, the processing results of the loader are marked as cacheable. * Calling this method and passing `false` turns off the loader's ability to * cache processing results. */ cacheable(cacheable?: boolean): void; /** * Tells if source map should be generated. Since generating source maps can be an expensive task, * you should check if source maps are actually requested. */ sourceMap: boolean; /** * The base path configured in Rspack config via `context`. */ rootContext: string; /** * The directory path of the currently processed module, which changes with the * location of each processed module. * For example, if the loader is processing `/project/src/components/Button.js`, * then the value of `this.context` would be `/project/src/components`. */ context: string | null; /** * The index in the loaders array of the current loader. */ loaderIndex: number; remainingRequest: string; currentRequest: string; previousRequest: string; /** * The module specifier string after being resolved. * For example, if a `resource.js` is processed by `loader1.js` and `loader2.js`, the value of * `this.request` will be `/path/to/loader1.js!/path/to/loader2.js!/path/to/resource.js`. */ request: string; /** * An array of all the loaders. It is writable in the pitch phase. * loaders = [{request: string, path: string, query: string, module: function}] * * In the example: * [ * { request: "/abc/loader1.js?xyz", * path: "/abc/loader1.js", * query: "?xyz", * module: [Function] * }, * { request: "/abc/node_modules/loader2/index.js", * path: "/abc/node_modules/loader2/index.js", * query: "", * module: [Function] * } * ] */ loaders: LoaderObject[]; /** * The value of `mode` is read when Rspack is run. * The possible values are: `'production'`, `'development'`, `'none'` */ mode?: Mode; /** * The current compilation target. Passed from `target` configuration options. */ target?: Target; /** * Whether HMR is enabled. */ hot?: boolean; /** * Get the options passed in by the loader's user. * @param schema To provide the best performance, Rspack does not perform the schema * validation. If your loader requires schema validation, please call scheme-utils or * zod on your own. */ getOptions(schema?: any): OptionsType; /** * Resolve a module specifier. * @param context The absolute path to a directory. This directory is used as the starting * location for resolving. * @param request The module specifier to be resolved. * @param callback A callback function that gives the resolved path. */ resolve(context: string, request: string, callback: (arg0: null | Error, arg1?: string | false, arg2?: ResolveRequest) => void): void; /** * Create a resolver like `this.resolve`. */ getResolve(options: Resolve): ((context: string, request: string, callback: ResolveCallback) => void) | ((context: string, request: string) => Promise); /** * Get the logger of this compilation, through which messages can be logged. */ getLogger(name: string): Logger; /** * Emit an error. Unlike `throw` and `this.callback(err)` in the loader, it does not * mark the current module as a compilation failure, it just adds an error to Rspack's * Compilation and displays it on the command line at the end of this compilation. */ emitError(error: Error): void; /** * Emit a warning. */ emitWarning(warning: Error): void; /** * Emit a new file. This method allows you to create new files during the loader execution. */ emitFile(name: string, content: string | Buffer, sourceMap?: string, assetInfo?: AssetInfo): void; /** * Add a file as a dependency on the loader results so that any changes to them can be listened to. * For example, `sass-loader`, `less-loader` use this trick to recompile when the imported style * files change. */ addDependency(file: string): void; /** * Alias of `this.addDependency()`. */ dependency(file: string): void; /** * Add the directory as a dependency for the loader results so that any changes to the * files in the directory can be listened to. */ addContextDependency(context: string): void; /** * Add a currently non-existent file as a dependency of the loader result, so that its * creation and any changes can be listened. For example, when a new file is created at * that path, it will trigger a rebuild. */ addMissingDependency(missing: string): void; /** * Removes all dependencies of the loader result. */ clearDependencies(): void; getDependencies(): string[]; getContextDependencies(): string[]; getMissingDependencies(): string[]; addBuildDependency(file: string): void; /** * Compile and execute a module at the build time. * This is an alternative lightweight solution for the child compiler. * `importModule` will return a Promise if no callback is provided. * * @example * ```ts * const modulePath = path.resolve(__dirname, 'some-module.ts'); * const moduleExports = await this.importModule(modulePath, { * // optional options * }); * ``` */ importModule(request: string, options: ImportModuleOptions | undefined, callback: (err?: null | Error, exports?: T) => any): void; importModule(request: string, options?: ImportModuleOptions): Promise; /** * Access to the `compilation` object's `inputFileSystem` property. */ fs: any; /** * This is an experimental API and maybe subject to change. * @experimental */ experiments: LoaderExperiments; /** * Access to some utilities. */ utils: { /** * Return a new request string using absolute paths when possible. */ absolutify: (context: string, request: string) => string; /** * Return a new request string avoiding absolute paths when possible. */ contextify: (context: string, request: string) => string; /** * Return a new Hash object from provided hash function. */ createHash: (algorithm?: string) => Hash; }; /** * The value depends on the loader configuration: * - If the current loader was configured with an options object, `this.query` will * point to that object. * - If the current loader has no options, but was invoked with a query string, this * will be a string starting with `?`. */ query: string | OptionsType; /** * A data object shared between the pitch and the normal phase. */ data: unknown; /** * Access to the current Compiler object of Rspack. */ _compiler: Compiler; /** * Access to the current Compilation object of Rspack. */ _compilation: Compilation; /** * @deprecated Hacky access to the Module object being loaded. */ _module: Module; /** * Note: This is not a Rspack public API, maybe removed in future. * Store some data from loader, and consume it from parser, it may be removed in the future * * @internal */ __internal__setParseMeta: (key: string, value: string) => void; } export type LoaderDefinitionFunction = (this: LoaderContext & ContextAdditions, content: string, sourceMap?: string | RawSourceMap, additionalData?: AdditionalData) => string | void | Buffer | Promise; export type PitchLoaderDefinitionFunction = (this: LoaderContext & ContextAdditions, remainingRequest: string, previousRequest: string, data: object) => string | void | Buffer | Promise; /** * Defines a loader for Rspack. * A loader is a transformer that converts various types of modules into Rspack * supported types. By using different kinds of loaders, you can extend Rspack to * process additional module types, including JSX, Markdown, Sass, Less, and more. * * @template OptionsType - The type of options that the loader accepts * @template ContextAdditions - Additional properties to add to the loader context * * @example * ```ts * import type { LoaderDefinition } from '@rspack/core'; * * type MyLoaderOptions = { * foo: string; * }; * * const myLoader: LoaderDefinition = function(source) { * return someOperation(source); * }; * * export default myLoader; * ``` */ export type LoaderDefinition = LoaderDefinitionFunction & { raw?: false; pitch?: PitchLoaderDefinitionFunction; }; export declare function createRawModuleRuleUses(uses: RuleSetUseItem | RuleSetUseItem[], path: string, options: ComposeJsUseOptions): RawModuleRuleUse[]; export type GetLoaderOptions = (o: RuleSetLoaderWithOptions['options'], options: ComposeJsUseOptions) => RuleSetLoaderWithOptions['options']; export declare function isUseSourceMap(devtool: RspackOptionsNormalized['devtool']): boolean; export declare function isUseSimpleSourceMap(devtool: RspackOptionsNormalized['devtool']): boolean;