diff --git a/declarations/LoaderContext.d.ts b/declarations/LoaderContext.d.ts new file mode 100644 index 00000000000..43b215e023e --- /dev/null +++ b/declarations/LoaderContext.d.ts @@ -0,0 +1,275 @@ +import type { SourceMap } from "../lib/NormalModule"; +import type { validate } from "schema-utils"; +import type { AssetInfo } from "../lib/Compilation"; +import type { ResolveOptionsWithDependencyType } from "../lib/ResolverFactory"; +import type Compilation from "../lib/Compilation"; +import type Compiler from "../lib/Compiler"; +import type NormalModule from "../lib/NormalModule"; +import type { InputFileSystem } from "../lib/util/fs"; +import type { Logger } from "../lib/logging/Logger"; +import type { + ImportModuleCallback, + ImportModuleOptions +} from "../lib/dependencies/LoaderPlugin"; +import type { Resolver } from "enhanced-resolve"; + +type ResolveCallback = Parameters[4]; +type Schema = Parameters[0]; + +/** These properties are added by the NormalModule */ +export interface NormalModuleLoaderContext { + version: number; + getOptions(): OptionsType; + getOptions(schema: Schema): OptionsType; + emitWarning(warning: Error): void; + emitError(error: Error): void; + getLogger(name?: string): Logger; + resolve(context: string, request: string, callback: ResolveCallback): any; + getResolve( + options?: ResolveOptionsWithDependencyType + ): ((context: string, request: string, callback: ResolveCallback) => void) & + ((context: string, request: string) => Promise); + emitFile( + name: string, + content: string, + sourceMap?: string, + assetInfo?: AssetInfo + ): void; + addBuildDependency(dep: string): void; + utils: { + absolutify: (context: string, request: string) => string; + contextify: (context: string, request: string) => string; + }; + rootContext: string; + fs: InputFileSystem; + sourceMap?: boolean; + mode: "development" | "production" | "none"; + webpack?: boolean; + _module?: NormalModule; + _compilation?: Compilation; + _compiler?: Compiler; +} + +/** These properties are added by the HotModuleReplacementPlugin */ +export interface HotModuleReplacementPluginLoaderContext { + hot?: boolean; +} + +/** These properties are added by the LoaderPlugin */ +export interface LoaderPluginLoaderContext { + /** + * Resolves the given request to a module, applies all configured loaders and calls + * back with the generated source, the sourceMap and the module instance (usually an + * instance of NormalModule). Use this function if you need to know the source code + * of another module to generate the result. + */ + loadModule( + request: string, + callback: ( + err: Error | null, + source: string, + sourceMap: any, + module: NormalModule + ) => void + ): void; + + importModule( + request: string, + options: ImportModuleOptions, + callback: ImportModuleCallback + ): void; + importModule(request: string, options?: ImportModuleOptions): Promise; +} + +/** The properties are added by https://github.com/webpack/loader-runner */ +export interface LoaderRunnerLoaderContext { + /** + * Add a directory as dependency of the loader result. + */ + addContextDependency(context: string): void; + + /** + * Adds a file as dependency of the loader result in order to make them watchable. + * For example, html-loader uses this technique as it finds src and src-set attributes. + * Then, it sets the url's for those attributes as dependencies of the html file that is parsed. + */ + addDependency(file: string): void; + + addMissingDependency(context: string): void; + + /** + * Make this loader async. + */ + async(): WebpackLoaderContextCallback; + + /** + * Make this loader result cacheable. By default it's cacheable. + * A cacheable loader must have a deterministic result, when inputs and dependencies haven't changed. + * This means the loader shouldn't have other dependencies than specified with this.addDependency. + * Most loaders are deterministic and cacheable. + */ + cacheable(flag?: boolean): void; + + callback: WebpackLoaderContextCallback; + + /** + * Remove all dependencies of the loader result. Even initial dependencies and these of other loaders. + */ + clearDependencies(): void; + + /** + * The directory of the module. Can be used as context for resolving other stuff. + * eg '/workspaces/ts-loader/examples/vanilla/src' + */ + context: string; + + readonly currentRequest: string; + + readonly data: any; + /** + * alias of addDependency + * Adds a file as dependency of the loader result in order to make them watchable. + * For example, html-loader uses this technique as it finds src and src-set attributes. + * Then, it sets the url's for those attributes as dependencies of the html file that is parsed. + */ + dependency(file: string): void; + + getContextDependencies(): string[]; + + getDependencies(): string[]; + + getMissingDependencies(): string[]; + + /** + * The index in the loaders array of the current loader. + * In the example: in loader1: 0, in loader2: 1 + */ + loaderIndex: number; + + readonly previousRequest: string; + + readonly query: string | OptionsType; + + readonly remainingRequest: string; + + readonly request: string; + + /** + * An array of all the loaders. It is writeable 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: { + request: string; + path: string; + query: string; + fragment: string; + options: object | string | undefined; + ident: string; + normal: Function | undefined; + pitch: Function | undefined; + raw: boolean | undefined; + data: object | undefined; + pitchExecuted: boolean; + normalExecuted: boolean; + }[]; + + /** + * The resource path. + * In the example: "/abc/resource.js" + */ + resourcePath: string; + + /** + * The resource query string. + * Example: "?query" + */ + resourceQuery: string; + + /** + * The resource fragment. + * Example: "#frag" + */ + resourceFragment: string; + + /** + * The resource inclusive query and fragment. + * Example: "/abc/resource.js?query#frag" + */ + resource: string; +} + +type AdditionalData = { + webpackAST: object; + [index: string]: any; +}; + +type WebpackLoaderContextCallback = ( + err: Error | undefined | null, + content?: string | Buffer, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData +) => void; + +type LoaderContext = NormalModuleLoaderContext & + LoaderRunnerLoaderContext & + LoaderPluginLoaderContext & + HotModuleReplacementPluginLoaderContext; + +type PitchLoaderDefinitionFunction = ( + this: LoaderContext & ContextAdditions, + remainingRequest: string, + previousRequest: string, + data: object +) => string | Buffer | Promise | void; + +type LoaderDefinitionFunction = ( + this: LoaderContext & ContextAdditions, + content: string, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData +) => string | Buffer | Promise | void; + +type RawLoaderDefinitionFunction = ( + this: LoaderContext & ContextAdditions, + content: Buffer, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData +) => string | Buffer | Promise | void; + +export type LoaderDefinition< + OptionsType = {}, + ContextAdditions = {} +> = LoaderDefinitionFunction & { + raw?: false; + pitch?: PitchLoaderDefinitionFunction; +}; + +export type RawLoaderDefinition< + OptionsType = {}, + ContextAdditions = {} +> = RawLoaderDefinitionFunction & { + raw: true; + pitch?: PitchLoaderDefinitionFunction; +}; + +export interface LoaderModule { + default?: + | RawLoaderDefinitionFunction + | LoaderDefinitionFunction; + raw?: false; + pitch?: PitchLoaderDefinitionFunction; +} diff --git a/declarations/index.d.ts b/declarations/index.d.ts new file mode 100644 index 00000000000..a9475f0809c --- /dev/null +++ b/declarations/index.d.ts @@ -0,0 +1,9 @@ +export type { + LoaderModule, + RawLoaderDefinition, + LoaderDefinition, + LoaderDefinitionFunction, + PitchLoaderDefinitionFunction, + RawLoaderDefinitionFunction, + LoaderContext +} from "./LoaderContext"; diff --git a/generate-types-config.js b/generate-types-config.js index 59d8b78920c..b1a47a8285e 100644 --- a/generate-types-config.js +++ b/generate-types-config.js @@ -1,7 +1,9 @@ module.exports = { nameMapping: { FsStats: /^Stats Import fs/, + validateFunction: /^validate Import/, Configuration: /^WebpackOptions / }, - exclude: [/^devServer in WebpackOptions /] + exclude: [/^devServer in WebpackOptions /], + include: [/^(_module|_compilation|_compiler) in NormalModuleLoaderContext /] }; diff --git a/lib/Compilation.js b/lib/Compilation.js index cfd12b3ad77..4518c112483 100644 --- a/lib/Compilation.js +++ b/lib/Compilation.js @@ -3993,8 +3993,8 @@ This prevents using hashes of each other and should be avoided.`); * from parent (or top level compiler) and creates a child Compilation * * @param {string} name name of the child compiler - * @param {OutputOptions} outputOptions // Need to convert config schema to types for this - * @param {Array} plugins webpack plugins that will be applied + * @param {OutputOptions=} outputOptions // Need to convert config schema to types for this + * @param {Array=} plugins webpack plugins that will be applied * @returns {Compiler} creates a child Compiler instance */ createChildCompiler(name, outputOptions, plugins) { diff --git a/lib/Compiler.js b/lib/Compiler.js index 7af7705efae..f97615deddd 100644 --- a/lib/Compiler.js +++ b/lib/Compiler.js @@ -931,8 +931,8 @@ ${other}`); * @param {Compilation} compilation the compilation * @param {string} compilerName the compiler's name * @param {number} compilerIndex the compiler's index - * @param {OutputOptions} outputOptions the output options - * @param {WebpackPluginInstance[]} plugins the plugins to apply + * @param {OutputOptions=} outputOptions the output options + * @param {WebpackPluginInstance[]=} plugins the plugins to apply * @returns {Compiler} a child compiler */ createChildCompiler( diff --git a/lib/EntryPlugin.js b/lib/EntryPlugin.js index 61c57daf4b3..054bc36d35d 100644 --- a/lib/EntryPlugin.js +++ b/lib/EntryPlugin.js @@ -17,7 +17,7 @@ class EntryPlugin { * * @param {string} context context path * @param {string} entry entry path - * @param {EntryOptions | string} options entry options (passing a string is deprecated) + * @param {EntryOptions | string=} options entry options (passing a string is deprecated) */ constructor(context, entry, options) { this.context = context; diff --git a/lib/NormalModule.js b/lib/NormalModule.js index 594c75c7e33..29320e89a08 100644 --- a/lib/NormalModule.js +++ b/lib/NormalModule.js @@ -41,10 +41,12 @@ const { contextify, absolutify } = require("./util/identifier"); const makeSerializable = require("./util/makeSerializable"); const memoize = require("./util/memoize"); -/** @typedef {import("source-map").RawSourceMap} SourceMap */ /** @typedef {import("webpack-sources").Source} Source */ +/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */ +/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */ /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */ /** @typedef {import("./ChunkGraph")} ChunkGraph */ +/** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */ /** @typedef {import("./DependencyTemplates")} DependencyTemplates */ /** @typedef {import("./Generator")} Generator */ @@ -60,10 +62,22 @@ const memoize = require("./util/memoize"); /** @typedef {import("./RequestShortener")} RequestShortener */ /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */ /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */ +/** @typedef {import("./logging/Logger").Logger} WebpackLogger */ /** @typedef {import("./util/Hash")} Hash */ /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */ /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */ +/** + * @typedef {Object} SourceMap + * @property {number} version + * @property {string[]} sources + * @property {string} mappings + * @property {string=} file + * @property {string=} sourceRoot + * @property {string[]=} sourcesContent + * @property {string[]=} names + */ + const getInvalidDependenciesModuleWarning = memoize(() => require("./InvalidDependenciesModuleWarning") ); @@ -421,7 +435,7 @@ class NormalModule extends Module { * @param {WebpackOptions} options webpack options * @param {Compilation} compilation the compilation * @param {InputFileSystem} fs file system from reading - * @returns {any} loader context + * @returns {NormalModuleLoaderContext} loader context */ createLoaderContext(resolver, options, compilation, fs) { const { requestShortener } = compilation.runtimeTemplate; diff --git a/lib/SourceMapDevToolPlugin.js b/lib/SourceMapDevToolPlugin.js index 3c89dd74776..ab066402381 100644 --- a/lib/SourceMapDevToolPlugin.js +++ b/lib/SourceMapDevToolPlugin.js @@ -16,7 +16,6 @@ const createHash = require("./util/createHash"); const { relative, dirname } = require("./util/fs"); const { absolutify } = require("./util/identifier"); -/** @typedef {import("source-map").RawSourceMap} SourceMap */ /** @typedef {import("webpack-sources").MapOptions} MapOptions */ /** @typedef {import("webpack-sources").Source} Source */ /** @typedef {import("../declarations/plugins/SourceMapDevToolPlugin").SourceMapDevToolPluginOptions} SourceMapDevToolPluginOptions */ @@ -26,6 +25,7 @@ const { absolutify } = require("./util/identifier"); /** @typedef {import("./Compilation").AssetInfo} AssetInfo */ /** @typedef {import("./Compiler")} Compiler */ /** @typedef {import("./Module")} Module */ +/** @typedef {import("./NormalModule").SourceMap} SourceMap */ /** @typedef {import("./util/Hash")} Hash */ const validate = createSchemaValidation( diff --git a/package.json b/package.json index ead003711a3..5e2ecb24307 100644 --- a/package.json +++ b/package.json @@ -92,7 +92,7 @@ "style-loader": "^2.0.0", "terser": "^5.5.0", "toml": "^3.0.0", - "tooling": "webpack/tooling#v1.18.0", + "tooling": "webpack/tooling#v1.19.0", "ts-loader": "^8.0.2", "typescript": "^4.2.0-beta", "url-loader": "^4.1.0", diff --git a/test/cases/compile/error-hide-stack/loader.js b/test/cases/compile/error-hide-stack/loader.js index 674e66c655f..b499c32a083 100644 --- a/test/cases/compile/error-hide-stack/loader.js +++ b/test/cases/compile/error-hide-stack/loader.js @@ -1,6 +1,8 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { var err = new Error("Message"); err.stack = "Stack"; + //@ts-expect-error hideStack is not a property on normal errors err.hideStack = true; throw err; }; diff --git a/test/cases/errors/load-module-cycle/loader.js b/test/cases/errors/load-module-cycle/loader.js index 19a8c699bc9..ed4a740b947 100644 --- a/test/cases/errors/load-module-cycle/loader.js +++ b/test/cases/errors/load-module-cycle/loader.js @@ -1,4 +1,5 @@ -exports.default = function(source) { +/** @type {import("../../../../").LoaderDefinitionFunction} */ +exports.default = function (source) { const ref = JSON.parse(source); const callback = this.async(); this.loadModule("../loader!" + ref, (err, source, sourceMap, module) => { diff --git a/test/cases/errors/load-module-error/error-loader.js b/test/cases/errors/load-module-error/error-loader.js index 114e742cb87..5758c7646c7 100644 --- a/test/cases/errors/load-module-error/error-loader.js +++ b/test/cases/errors/load-module-error/error-loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../types").LoaderDefinition} */ module.exports = function(source) { const callback = this.async(); callback(new Error("err: abc")); diff --git a/test/cases/errors/load-module-error/loader.js b/test/cases/errors/load-module-error/loader.js index 6001a39c5df..3eb4fa42c63 100644 --- a/test/cases/errors/load-module-error/loader.js +++ b/test/cases/errors/load-module-error/loader.js @@ -1,4 +1,5 @@ -exports.default = function(source) { +/** @type {import("../../../../").LoaderDefinitionFunction} */ +exports.default = function (source) { const callback = this.async(); const ref = JSON.parse(source); this.loadModule("./error-loader!" + ref, (err, source, sourceMap, module) => { diff --git a/test/cases/errors/loader-error-warning/error-loader.js b/test/cases/errors/loader-error-warning/error-loader.js index 175192c08da..8c63082d417 100644 --- a/test/cases/errors/loader-error-warning/error-loader.js +++ b/test/cases/errors/loader-error-warning/error-loader.js @@ -1,4 +1,6 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { + //@ts-expect-error errors must be Errors, string is not recommended and should lead to type error this.emitError(this.query.substr(1)); return source; -} +}; diff --git a/test/cases/errors/loader-error-warning/warning-loader.js b/test/cases/errors/loader-error-warning/warning-loader.js index 05142648f6c..adc1a120a84 100644 --- a/test/cases/errors/loader-error-warning/warning-loader.js +++ b/test/cases/errors/loader-error-warning/warning-loader.js @@ -1,4 +1,6 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { + //@ts-expect-error warnings must be Errors, string is not recommended and should lead to type error this.emitWarning(this.query.substr(1)); return source; -} +}; diff --git a/test/cases/loaders/async/loaders/asyncloader.js b/test/cases/loaders/async/loaders/asyncloader.js index d9be05de326..c6c0eb8d422 100644 --- a/test/cases/loaders/async/loaders/asyncloader.js +++ b/test/cases/loaders/async/loaders/asyncloader.js @@ -1,8 +1,10 @@ -module.exports = function(content) { +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (content) { var cb = this.async(); - if(!cb) throw new Error("Loader should allow async mode"); - if(cb !== this.callback) throw new Error("result of this.async() should be equal to this.callback"); - process.nextTick(function() { + if (!cb) throw new Error("Loader should allow async mode"); + if (cb !== this.callback) + throw new Error("result of this.async() should be equal to this.callback"); + process.nextTick(function () { cb(null, content); }); -}; \ No newline at end of file +}; diff --git a/test/cases/loaders/async/loaders/syncloader.js b/test/cases/loaders/async/loaders/syncloader.js index 0356c896f23..fe0c014dba4 100644 --- a/test/cases/loaders/async/loaders/syncloader.js +++ b/test/cases/loaders/async/loaders/syncloader.js @@ -1,3 +1,4 @@ -module.exports = function(content) { +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (content) { return content; -}; \ No newline at end of file +}; diff --git a/test/cases/loaders/emit-file/loader.js b/test/cases/loaders/emit-file/loader.js index 126cb485d51..c53b3e18fbc 100644 --- a/test/cases/loaders/emit-file/loader.js +++ b/test/cases/loaders/emit-file/loader.js @@ -1,4 +1,5 @@ -module.exports = function(content) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (content) { this.emitFile("extra-file.js", content); return ""; -} +}; diff --git a/test/cases/loaders/issue-10725/loader.js b/test/cases/loaders/issue-10725/loader.js index 7c3bb85cd93..af9af2d2418 100644 --- a/test/cases/loaders/issue-10725/loader.js +++ b/test/cases/loaders/issue-10725/loader.js @@ -2,22 +2,25 @@ const { getRemainingRequest, stringifyRequest } = require("loader-utils"); const loaderPath = require.resolve("./loader"); +/** @type {import("../../../../").LoaderDefinition} */ module.exports = function () { if (this.query === "?load") { return ` import { answer } from "./lib"; export default answer; -` +`; } const matchResource = `${this.resourcePath}.js`; const loader = `${loaderPath}?load`; const remaining = getRemainingRequest(this); - const request = JSON.parse(stringifyRequest(this, `${matchResource}!=!${loader}!${remaining}`)); + const request = JSON.parse( + stringifyRequest(this, `${matchResource}!=!${loader}!${remaining}`) + ); this.async(); this.loadModule(request, (err, source) => { - this.callback(err, source) + this.callback(err, source); }); }; diff --git a/test/cases/loaders/module-description-file/reverseloader.js b/test/cases/loaders/module-description-file/reverseloader.js index 2983d5650c6..4cbb644664a 100644 --- a/test/cases/loaders/module-description-file/reverseloader.js +++ b/test/cases/loaders/module-description-file/reverseloader.js @@ -1,3 +1,4 @@ -module.exports = function(content) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (content) { return content.split("").reverse().join(""); -} +}; diff --git a/test/cases/loaders/query/loaders/queryloader.js b/test/cases/loaders/query/loaders/queryloader.js index 8d606f560f8..f9bb23e1f55 100644 --- a/test/cases/loaders/query/loaders/queryloader.js +++ b/test/cases/loaders/query/loaders/queryloader.js @@ -1,7 +1,11 @@ -module.exports = function(content) { - return "module.exports = " + JSON.stringify({ - resourceQuery: this.resourceQuery, - query: this.query, - prev: content - }); -} +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (content) { + return ( + "module.exports = " + + JSON.stringify({ + resourceQuery: this.resourceQuery, + query: this.query, + prev: content + }) + ); +}; diff --git a/test/cases/loaders/resolve/loader.js b/test/cases/loaders/resolve/loader.js index 3bb4b23d839..53fc4aaf2f1 100644 --- a/test/cases/loaders/resolve/loader.js +++ b/test/cases/loaders/resolve/loader.js @@ -1,5 +1,6 @@ const path = require("path"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const resolve1 = this.getResolve(); const resolve2 = this.getResolve({ extensions: [".xyz", ".js"] diff --git a/test/cases/loaders/utils/loader.js b/test/cases/loaders/utils/loader.js index 3ee7d109250..2d9e6e37073 100644 --- a/test/cases/loaders/utils/loader.js +++ b/test/cases/loaders/utils/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").LoaderDefinition} */ module.exports = function () { return `module.exports = { request1: ${JSON.stringify( diff --git a/test/cases/parsing/context/loaders/queryloader.js b/test/cases/parsing/context/loaders/queryloader.js index 02707b2ba37..f9bb23e1f55 100644 --- a/test/cases/parsing/context/loaders/queryloader.js +++ b/test/cases/parsing/context/loaders/queryloader.js @@ -1,7 +1,11 @@ -module.exports = function(content) { - return "module.exports = " + JSON.stringify({ - resourceQuery: this.resourceQuery, - query: this.query, - prev: content - }); +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (content) { + return ( + "module.exports = " + + JSON.stringify({ + resourceQuery: this.resourceQuery, + query: this.query, + prev: content + }) + ); }; diff --git a/test/cases/parsing/precreated-ast/ast-loader.js b/test/cases/parsing/precreated-ast/ast-loader.js index 6293e064441..e150377260e 100644 --- a/test/cases/parsing/precreated-ast/ast-loader.js +++ b/test/cases/parsing/precreated-ast/ast-loader.js @@ -3,7 +3,8 @@ const acorn = require("acorn"); const acornParser = acorn.Parser; -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { const comments = []; const ast = acornParser.parse(source, { @@ -15,9 +16,12 @@ module.exports = function(source) { }); // change something to test if it's really used + //@ts-ignore ast.body[0].expression.right.arguments[0].value = "./ok"; - ast.body[0].expression.right.arguments[0].raw = "\"./ok\""; + //@ts-ignore + ast.body[0].expression.right.arguments[0].raw = '"./ok"'; + //@ts-ignore ast.comments = comments; this.callback(null, source, null, { webpackAST: ast diff --git a/test/cases/resolving/context/loaders/queryloader.js b/test/cases/resolving/context/loaders/queryloader.js index 8d606f560f8..f9bb23e1f55 100644 --- a/test/cases/resolving/context/loaders/queryloader.js +++ b/test/cases/resolving/context/loaders/queryloader.js @@ -1,7 +1,11 @@ -module.exports = function(content) { - return "module.exports = " + JSON.stringify({ - resourceQuery: this.resourceQuery, - query: this.query, - prev: content - }); -} +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (content) { + return ( + "module.exports = " + + JSON.stringify({ + resourceQuery: this.resourceQuery, + query: this.query, + prev: content + }) + ); +}; diff --git a/test/cases/wasm/two-files-loader/wrapper-loader.js b/test/cases/wasm/two-files-loader/wrapper-loader.js index 736d6fa0cf8..827857a6b8a 100644 --- a/test/cases/wasm/two-files-loader/wrapper-loader.js +++ b/test/cases/wasm/two-files-loader/wrapper-loader.js @@ -1,5 +1,6 @@ const stringifyRequest = require("loader-utils").stringifyRequest; +/** @type {import("../../../../").PitchLoaderDefinitionFunction} */ module.exports.pitch = function (remainingRequest) { return ` import { getString as _getString, memory } from ${stringifyRequest( diff --git a/test/cases/wasm/two-files-loader/wrapper-loader2.js b/test/cases/wasm/two-files-loader/wrapper-loader2.js index 478a1f4f427..dde8826aa73 100644 --- a/test/cases/wasm/two-files-loader/wrapper-loader2.js +++ b/test/cases/wasm/two-files-loader/wrapper-loader2.js @@ -1,5 +1,6 @@ const stringifyRequest = require("loader-utils").stringifyRequest; +/** @type {import("../../../../").PitchLoaderDefinitionFunction} */ module.exports.pitch = function (remainingRequest) { return ` import { getString as _getString, memory } from ${stringifyRequest( diff --git a/test/configCases/cache-dependencies/managed-items/loader.js b/test/configCases/cache-dependencies/managed-items/loader.js index 82546670808..3a6935623f6 100644 --- a/test/configCases/cache-dependencies/managed-items/loader.js +++ b/test/configCases/cache-dependencies/managed-items/loader.js @@ -1,4 +1,6 @@ const path = require("path"); + +/** @type {import("../../../../").LoaderDefinition} */ module.exports = function (source) { this.addDependency(path.resolve(__dirname, "node_modules/package/extra.js")); this.addDependency(path.resolve(__dirname, "extra.js")); diff --git a/test/configCases/context-replacement/d/queryloader.js b/test/configCases/context-replacement/d/queryloader.js index 88a2fd607bc..821519145eb 100644 --- a/test/configCases/context-replacement/d/queryloader.js +++ b/test/configCases/context-replacement/d/queryloader.js @@ -1,7 +1,11 @@ -module.exports = function(content) { - return "module.exports = " + JSON.stringify({ - resourceQuery: this.resourceQuery, - query: this.query, - prev: content.replace(/\r\n?/g, "\n") - }); +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (content) { + return ( + "module.exports = " + + JSON.stringify({ + resourceQuery: this.resourceQuery, + query: this.query, + prev: content.replace(/\r\n?/g, "\n") + }) + ); }; diff --git a/test/configCases/deprecations/invalid-dependencies/loader.js b/test/configCases/deprecations/invalid-dependencies/loader.js index 47a39616b26..71212ed09b8 100644 --- a/test/configCases/deprecations/invalid-dependencies/loader.js +++ b/test/configCases/deprecations/invalid-dependencies/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").LoaderDefinition} */ module.exports = function (source) { this.addDependency("loader.js"); this.addDependency("../**/dir/*.js"); diff --git a/test/configCases/dll-plugin/0-create-dll/g-loader.js b/test/configCases/dll-plugin/0-create-dll/g-loader.js index 6e64f4af6bb..c6d8a635121 100644 --- a/test/configCases/dll-plugin/0-create-dll/g-loader.js +++ b/test/configCases/dll-plugin/0-create-dll/g-loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return source; }; diff --git a/test/configCases/inner-graph/_helpers/entryLoader.js b/test/configCases/inner-graph/_helpers/entryLoader.js index 992500b06fa..7e129b81030 100644 --- a/test/configCases/inner-graph/_helpers/entryLoader.js +++ b/test/configCases/inner-graph/_helpers/entryLoader.js @@ -1,4 +1,5 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const { name, expect, usedExports } = JSON.parse(this.query.slice(1)); return [ `if (Math.random() < 0) require(${JSON.stringify( diff --git a/test/configCases/inner-graph/_helpers/testModuleLoader.js b/test/configCases/inner-graph/_helpers/testModuleLoader.js index 1742c4ad429..b6d54748dda 100644 --- a/test/configCases/inner-graph/_helpers/testModuleLoader.js +++ b/test/configCases/inner-graph/_helpers/testModuleLoader.js @@ -1,4 +1,5 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const usedExports = JSON.parse(this.query.slice(1)); return [ `import { ${usedExports diff --git a/test/configCases/layer/rules/loader.js b/test/configCases/layer/rules/loader.js index 34dbc1b1703..7e5acde631c 100644 --- a/test/configCases/layer/rules/loader.js +++ b/test/configCases/layer/rules/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").LoaderDefinition<{ value: any }>} */ module.exports = function (source) { const options = this.getOptions(); return `${source} diff --git a/test/configCases/loader-import-module/css/loader.js b/test/configCases/loader-import-module/css/loader.js index d9b5022ab4a..2dae62a4065 100644 --- a/test/configCases/loader-import-module/css/loader.js +++ b/test/configCases/loader-import-module/css/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").PitchLoaderDefinitionFunction} */ exports.pitch = async function (remaining) { const result = await this.importModule( this.resourcePath + ".webpack[javascript/auto]" + "!=!" + remaining, diff --git a/test/configCases/loaders/generate-ident/loader1.js b/test/configCases/loaders/generate-ident/loader1.js index 42fea46336a..0d2fcc8b593 100644 --- a/test/configCases/loaders/generate-ident/loader1.js +++ b/test/configCases/loaders/generate-ident/loader1.js @@ -1,3 +1,6 @@ -module.exports.pitch = function(remainingRequest) { - return "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");"; +/** @type {import("../../../../").PitchLoaderDefinitionFunction} */ +module.exports.pitch = function (remainingRequest) { + return ( + "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");" + ); }; diff --git a/test/configCases/loaders/generate-ident/loader2.js b/test/configCases/loaders/generate-ident/loader2.js index b5b133a9208..40788042801 100644 --- a/test/configCases/loaders/generate-ident/loader2.js +++ b/test/configCases/loaders/generate-ident/loader2.js @@ -1,3 +1,6 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ f(): any }>} */ +module.exports = function (source) { + if (typeof this.query === "string") + throw new Error("query must be an object"); return "module.exports = " + JSON.stringify(this.query.f()); }; diff --git a/test/configCases/loaders/hot-in-context/loader.js b/test/configCases/loaders/hot-in-context/loader.js index b497b8bc45e..608faaddb21 100644 --- a/test/configCases/loaders/hot-in-context/loader.js +++ b/test/configCases/loaders/hot-in-context/loader.js @@ -1,3 +1,4 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition}} */ +module.exports = function () { return `module.exports = ${JSON.stringify(!!this.hot)};`; -} +}; diff --git a/test/configCases/loaders/mode-default/loader.js b/test/configCases/loaders/mode-default/loader.js index 0083d38fd1b..b9c10626bc4 100644 --- a/test/configCases/loaders/mode-default/loader.js +++ b/test/configCases/loaders/mode-default/loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return `module.exports = "${this.mode}";`; }; diff --git a/test/configCases/loaders/mode-development/loader.js b/test/configCases/loaders/mode-development/loader.js index 0083d38fd1b..b9c10626bc4 100644 --- a/test/configCases/loaders/mode-development/loader.js +++ b/test/configCases/loaders/mode-development/loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return `module.exports = "${this.mode}";`; }; diff --git a/test/configCases/loaders/mode-none/loader.js b/test/configCases/loaders/mode-none/loader.js index 0083d38fd1b..b9c10626bc4 100644 --- a/test/configCases/loaders/mode-none/loader.js +++ b/test/configCases/loaders/mode-none/loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return `module.exports = "${this.mode}";`; }; diff --git a/test/configCases/loaders/mode-production/loader.js b/test/configCases/loaders/mode-production/loader.js index 0083d38fd1b..b9c10626bc4 100644 --- a/test/configCases/loaders/mode-production/loader.js +++ b/test/configCases/loaders/mode-production/loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return `module.exports = "${this.mode}";`; }; diff --git a/test/configCases/loaders/options/loader-1.js b/test/configCases/loaders/options/loader-1.js index f27763418ab..18e183cbbb0 100644 --- a/test/configCases/loaders/options/loader-1.js +++ b/test/configCases/loaders/options/loader-1.js @@ -1,6 +1,7 @@ -const schema = require("./loader-1.options"); +const schema = require("./loader-1.options.json"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const options = this.getOptions(schema); const json = JSON.stringify(options) diff --git a/test/configCases/loaders/options/loader-2.js b/test/configCases/loaders/options/loader-2.js index b1690265227..faea214da83 100644 --- a/test/configCases/loaders/options/loader-2.js +++ b/test/configCases/loaders/options/loader-2.js @@ -1,6 +1,7 @@ -const schema = require("./loader-2.options"); +const schema = require("./loader-2.options.json"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const options = this.getOptions(schema); const json = JSON.stringify(options) diff --git a/test/configCases/loaders/options/loader.js b/test/configCases/loaders/options/loader.js index 5b9386651be..d1bc02fcd3c 100644 --- a/test/configCases/loaders/options/loader.js +++ b/test/configCases/loaders/options/loader.js @@ -1,9 +1,10 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const options = this.getOptions(); const json = JSON.stringify(options) - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); + .replace(/\u2028/g, "\\u2028") + .replace(/\u2029/g, "\\u2029"); return `module.exports = ${json}`; }; diff --git a/test/configCases/loaders/pre-post-loader/loader1.js b/test/configCases/loaders/pre-post-loader/loader1.js index 71df71135dd..bf6d1335221 100644 --- a/test/configCases/loaders/pre-post-loader/loader1.js +++ b/test/configCases/loaders/pre-post-loader/loader1.js @@ -1,3 +1,4 @@ -module.exports = function(source) { - return source + "module.exports += \" loader1\";\n"; +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { + return source + 'module.exports += " loader1";\n'; }; diff --git a/test/configCases/loaders/pre-post-loader/loader2.js b/test/configCases/loaders/pre-post-loader/loader2.js index 91497b0978b..b611c84f62b 100644 --- a/test/configCases/loaders/pre-post-loader/loader2.js +++ b/test/configCases/loaders/pre-post-loader/loader2.js @@ -1,3 +1,4 @@ -module.exports = function(source) { - return source + "module.exports += \" loader2\";\n"; +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { + return source + 'module.exports += " loader2";\n'; }; diff --git a/test/configCases/loaders/pre-post-loader/loader3.js b/test/configCases/loaders/pre-post-loader/loader3.js index 32f164287a0..ec526cbac53 100644 --- a/test/configCases/loaders/pre-post-loader/loader3.js +++ b/test/configCases/loaders/pre-post-loader/loader3.js @@ -1,3 +1,4 @@ -module.exports = function(source) { - return source + "module.exports += \" loader3\";\n"; +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { + return source + 'module.exports += " loader3";\n'; }; diff --git a/test/configCases/loaders/remaining-request/loader1.js b/test/configCases/loaders/remaining-request/loader1.js index 42fea46336a..0d2fcc8b593 100644 --- a/test/configCases/loaders/remaining-request/loader1.js +++ b/test/configCases/loaders/remaining-request/loader1.js @@ -1,3 +1,6 @@ -module.exports.pitch = function(remainingRequest) { - return "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");"; +/** @type {import("../../../../").PitchLoaderDefinitionFunction} */ +module.exports.pitch = function (remainingRequest) { + return ( + "module.exports = require(" + JSON.stringify("!!" + remainingRequest) + ");" + ); }; diff --git a/test/configCases/loaders/remaining-request/loader2.js b/test/configCases/loaders/remaining-request/loader2.js index b5b133a9208..40788042801 100644 --- a/test/configCases/loaders/remaining-request/loader2.js +++ b/test/configCases/loaders/remaining-request/loader2.js @@ -1,3 +1,6 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ f(): any }>} */ +module.exports = function (source) { + if (typeof this.query === "string") + throw new Error("query must be an object"); return "module.exports = " + JSON.stringify(this.query.f()); }; diff --git a/test/configCases/module-name/different-issuers-for-same-module/loader-a.js b/test/configCases/module-name/different-issuers-for-same-module/loader-a.js index bd8581ca4a4..4e8352ee90e 100644 --- a/test/configCases/module-name/different-issuers-for-same-module/loader-a.js +++ b/test/configCases/module-name/different-issuers-for-same-module/loader-a.js @@ -1,3 +1,4 @@ -module.exports = function(src) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (src) { return `module.exports = "loader-a" + module.id`; }; diff --git a/test/configCases/module-name/different-issuers-for-same-module/loader-b.js b/test/configCases/module-name/different-issuers-for-same-module/loader-b.js index 5365e2fd355..7fa193f020f 100644 --- a/test/configCases/module-name/different-issuers-for-same-module/loader-b.js +++ b/test/configCases/module-name/different-issuers-for-same-module/loader-b.js @@ -1,3 +1,4 @@ -module.exports = function(src) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (src) { return `module.exports = "loader-b" + module.id`; }; diff --git a/test/configCases/performance/many-async-imports/reexport.loader.js b/test/configCases/performance/many-async-imports/reexport.loader.js index f44ceced67a..3105e517fef 100644 --- a/test/configCases/performance/many-async-imports/reexport.loader.js +++ b/test/configCases/performance/many-async-imports/reexport.loader.js @@ -1,7 +1,8 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { var str = "export default Promise.all([\n"; - for(var i = 0; i < 6; i++) { - for(var j = 0; j < 2; j++) { + for (var i = 0; i < 6; i++) { + for (var j = 0; j < 2; j++) { str += `import("./reexport.loader.js!?${i}"),\n`; } } diff --git a/test/configCases/performance/many-exports/file.loader.js b/test/configCases/performance/many-exports/file.loader.js index 6ec2268c91d..1dd13c65f5c 100644 --- a/test/configCases/performance/many-exports/file.loader.js +++ b/test/configCases/performance/many-exports/file.loader.js @@ -1,7 +1,8 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { var str = ""; - for(var i = 0; i < 1000; i++) { + for (var i = 0; i < 1000; i++) { str += `export var a${i} = ${i};\n`; } return str; -} +}; diff --git a/test/configCases/performance/many-exports/reexport.loader.js b/test/configCases/performance/many-exports/reexport.loader.js index af755e8686a..e4a2a31352a 100644 --- a/test/configCases/performance/many-exports/reexport.loader.js +++ b/test/configCases/performance/many-exports/reexport.loader.js @@ -1,9 +1,10 @@ -module.exports = function() { - var str = "import * as i from \"./file.loader.js!\";\n"; +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { + var str = 'import * as i from "./file.loader.js!";\n'; str += "var sum = 0;\n"; - for(var i = 0; i < 1000; i++) { + for (var i = 0; i < 1000; i++) { str += `sum += i.a${i};\n`; } str += "export default sum;\n"; return str; -} +}; diff --git a/test/configCases/plugins/loader-options-plugin/loader.js b/test/configCases/plugins/loader-options-plugin/loader.js index 7374ef2b557..8fcf0774460 100644 --- a/test/configCases/plugins/loader-options-plugin/loader.js +++ b/test/configCases/plugins/loader-options-plugin/loader.js @@ -1,6 +1,10 @@ -module.exports = function() { - return "module.exports = " + JSON.stringify({ - minimize: this.minimize, - jsfile: this.jsfile - }); +/** @type {import("../../../../").LoaderDefinition<{}, { minimize: boolean, jsfile: boolean }>} */ +module.exports = function () { + return ( + "module.exports = " + + JSON.stringify({ + minimize: this.minimize, + jsfile: this.jsfile + }) + ); }; diff --git a/test/configCases/race-conditions/load-module/loader.js b/test/configCases/race-conditions/load-module/loader.js index 444c2c9dad3..b741c194e99 100644 --- a/test/configCases/race-conditions/load-module/loader.js +++ b/test/configCases/race-conditions/load-module/loader.js @@ -1,4 +1,5 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { const callback = this.async(); let finished = false; this.loadModule("./module.js", (err, result) => { diff --git a/test/configCases/rebuild/finishModules/loader.js b/test/configCases/rebuild/finishModules/loader.js index 80d125d3902..347e3b5be32 100644 --- a/test/configCases/rebuild/finishModules/loader.js +++ b/test/configCases/rebuild/finishModules/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").LoaderDefinition<{}, { shouldReplace: boolean }>} */ module.exports = function (source) { if (this.shouldReplace) { this._module.buildInfo._isReplaced = true; diff --git a/test/configCases/rebuild/rebuildWithNewDependencies/loader.js b/test/configCases/rebuild/rebuildWithNewDependencies/loader.js index fc39654810e..f33697b4f1a 100644 --- a/test/configCases/rebuild/rebuildWithNewDependencies/loader.js +++ b/test/configCases/rebuild/rebuildWithNewDependencies/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").LoaderDefinition<{}, { shouldReplace: boolean }>} */ module.exports = function (source) { if (this.shouldReplace) { this._module.buildInfo._isReplaced = true; diff --git a/test/configCases/records/issue-295/loader.js b/test/configCases/records/issue-295/loader.js index 6e64f4af6bb..c6d8a635121 100644 --- a/test/configCases/records/issue-295/loader.js +++ b/test/configCases/records/issue-295/loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return source; }; diff --git a/test/configCases/resolve-merging/override/loader.js b/test/configCases/resolve-merging/override/loader.js index 7e124f2381d..961891c5e19 100644 --- a/test/configCases/resolve-merging/override/loader.js +++ b/test/configCases/resolve-merging/override/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").LoaderDefinition} */ module.exports = async function () { const defaultResolve = this.getResolve({}); const overrideResolve = this.getResolve({ @@ -20,6 +21,7 @@ module.exports = async function () { expect(await defaultResolve(undefined, "package2").catch(e => "ok")).toBe( "ok" ); + // @ts-expect-error undefined should not be a valid type expect(await defaultResolve(undefined).catch(e => "ok")).toBe("ok"); return ` export { default as a } from ${JSON.stringify(resolved1)}; diff --git a/test/configCases/rule-set/chaining/loader.js b/test/configCases/rule-set/chaining/loader.js index f78d43c0b78..84836e5dae5 100644 --- a/test/configCases/rule-set/chaining/loader.js +++ b/test/configCases/rule-set/chaining/loader.js @@ -1,8 +1,8 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ get(): string }>} */ +module.exports = function (source) { var query = this.query; - if(typeof query === "object" && typeof query.get === "function") { + if (typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; - diff --git a/test/configCases/rule-set/compiler/loader.js b/test/configCases/rule-set/compiler/loader.js index 196d1ef49db..b57f18e5dae 100644 --- a/test/configCases/rule-set/compiler/loader.js +++ b/test/configCases/rule-set/compiler/loader.js @@ -1,4 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return "module.exports = " + JSON.stringify("loader matched"); }; - diff --git a/test/configCases/rule-set/custom/loader.js b/test/configCases/rule-set/custom/loader.js index f78d43c0b78..84836e5dae5 100644 --- a/test/configCases/rule-set/custom/loader.js +++ b/test/configCases/rule-set/custom/loader.js @@ -1,8 +1,8 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ get(): string }>} */ +module.exports = function (source) { var query = this.query; - if(typeof query === "object" && typeof query.get === "function") { + if (typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; - diff --git a/test/configCases/rule-set/query/loader.js b/test/configCases/rule-set/query/loader.js index f78d43c0b78..84836e5dae5 100644 --- a/test/configCases/rule-set/query/loader.js +++ b/test/configCases/rule-set/query/loader.js @@ -1,8 +1,8 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ get(): string }>} */ +module.exports = function (source) { var query = this.query; - if(typeof query === "object" && typeof query.get === "function") { + if (typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; - diff --git a/test/configCases/rule-set/simple-use-array-fn/loader.js b/test/configCases/rule-set/simple-use-array-fn/loader.js index f78d43c0b78..84836e5dae5 100644 --- a/test/configCases/rule-set/simple-use-array-fn/loader.js +++ b/test/configCases/rule-set/simple-use-array-fn/loader.js @@ -1,8 +1,8 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ get(): string }>} */ +module.exports = function (source) { var query = this.query; - if(typeof query === "object" && typeof query.get === "function") { + if (typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; - diff --git a/test/configCases/rule-set/simple-use-fn-array/loader.js b/test/configCases/rule-set/simple-use-fn-array/loader.js index f78d43c0b78..84836e5dae5 100644 --- a/test/configCases/rule-set/simple-use-fn-array/loader.js +++ b/test/configCases/rule-set/simple-use-fn-array/loader.js @@ -1,8 +1,8 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ get(): string }>} */ +module.exports = function (source) { var query = this.query; - if(typeof query === "object" && typeof query.get === "function") { + if (typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; - diff --git a/test/configCases/rule-set/simple/loader.js b/test/configCases/rule-set/simple/loader.js index f78d43c0b78..84836e5dae5 100644 --- a/test/configCases/rule-set/simple/loader.js +++ b/test/configCases/rule-set/simple/loader.js @@ -1,8 +1,8 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition<{ get(): string }>} */ +module.exports = function (source) { var query = this.query; - if(typeof query === "object" && typeof query.get === "function") { + if (typeof query === "object" && typeof query.get === "function") { query = query.get(); } return source + "\nmodule.exports.push(" + JSON.stringify(query) + ");"; }; - diff --git a/test/configCases/source-map/no-source-map/loader.js b/test/configCases/source-map/no-source-map/loader.js index 5cac8966d3a..84613ab8e99 100644 --- a/test/configCases/source-map/no-source-map/loader.js +++ b/test/configCases/source-map/no-source-map/loader.js @@ -1,4 +1,5 @@ const path = require("path"); +/** @type {import("../../../../").LoaderDefinition} */ module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, @@ -6,6 +7,7 @@ module.exports = function () { sourceRoot: path.join(__dirname, "folder"), sources: ["test1.txt"], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/configCases/source-map/relative-source-maps-by-loader/loader-no-source-root.js b/test/configCases/source-map/relative-source-maps-by-loader/loader-no-source-root.js index e30048a3e41..f2ca2e44e87 100644 --- a/test/configCases/source-map/relative-source-maps-by-loader/loader-no-source-root.js +++ b/test/configCases/source-map/relative-source-maps-by-loader/loader-no-source-root.js @@ -1,10 +1,12 @@ const path = require("path"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, file: "/should/be/removed", sources: [path.join(__dirname, "folder", "test5.txt")], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/configCases/source-map/relative-source-maps-by-loader/loader-pre-relative.js b/test/configCases/source-map/relative-source-maps-by-loader/loader-pre-relative.js index 6fe9431cedb..e70ef8ec6ca 100644 --- a/test/configCases/source-map/relative-source-maps-by-loader/loader-pre-relative.js +++ b/test/configCases/source-map/relative-source-maps-by-loader/loader-pre-relative.js @@ -1,9 +1,11 @@ -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, file: "/should/be/removed", sources: ["webpack://./folder/test6.txt"], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-2-slash.js b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-2-slash.js index e5c552d40f9..eb49d6a3ce5 100644 --- a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-2-slash.js +++ b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-2-slash.js @@ -1,11 +1,13 @@ const path = require("path"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, file: "/should/be/removed", sourceRoot: path.join(__dirname, "folder") + "/", sources: ["/test4.txt"], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-slash.js b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-slash.js index 0641ad6d563..2fb7f62e1f5 100644 --- a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-slash.js +++ b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-slash.js @@ -1,11 +1,13 @@ const path = require("path"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, file: "/should/be/removed", sourceRoot: path.join(__dirname, "folder") + "/", sources: ["test3.txt"], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-source-slash.js b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-source-slash.js index dbb0e20bb53..5e25c38b2b3 100644 --- a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-source-slash.js +++ b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root-source-slash.js @@ -1,11 +1,13 @@ const path = require("path"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, file: "/should/be/removed", sourceRoot: path.join(__dirname, "folder"), sources: ["/test2.txt"], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root.js b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root.js index a46ea3ff546..84613ab8e99 100644 --- a/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root.js +++ b/test/configCases/source-map/relative-source-maps-by-loader/loader-source-root.js @@ -1,11 +1,13 @@ const path = require("path"); -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { this.callback(null, "module.exports = 'ok';", { version: 3, file: "/should/be/removed", sourceRoot: path.join(__dirname, "folder"), sources: ["test1.txt"], sourcesContent: ["Test"], + names: [], mappings: "AAAA" }); }; diff --git a/test/fixtures/count-loader.js b/test/fixtures/count-loader.js index ced2018eef9..9da5ce227be 100644 --- a/test/fixtures/count-loader.js +++ b/test/fixtures/count-loader.js @@ -1,5 +1,6 @@ let counter = 0; -module.exports = function() { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () { return `module.exports = ${counter++};`; }; diff --git a/test/fixtures/delay-loader.js b/test/fixtures/delay-loader.js index 3c6573548fe..01e71f3fb6d 100644 --- a/test/fixtures/delay-loader.js +++ b/test/fixtures/delay-loader.js @@ -1,6 +1,7 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { var cb = this.async(); - setTimeout(function() { + setTimeout(function () { cb(null, source); }, 500); -}; \ No newline at end of file +}; diff --git a/test/fixtures/errors/add-comment-loader.js b/test/fixtures/errors/add-comment-loader.js index 1cfa533d6a7..586bfbce576 100644 --- a/test/fixtures/errors/add-comment-loader.js +++ b/test/fixtures/errors/add-comment-loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return source + "// some comment"; }; diff --git a/test/fixtures/errors/async-error-loader.js b/test/fixtures/errors/async-error-loader.js index a0eba8a9d54..9826e36c3b7 100644 --- a/test/fixtures/errors/async-error-loader.js +++ b/test/fixtures/errors/async-error-loader.js @@ -1,4 +1,5 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { const callback = this.async(); const error = new Error("this is a callback error"); callback(error, source); diff --git a/test/fixtures/errors/emit-error-loader.js b/test/fixtures/errors/emit-error-loader.js index 57164e2206c..1cd648e665d 100644 --- a/test/fixtures/errors/emit-error-loader.js +++ b/test/fixtures/errors/emit-error-loader.js @@ -1,4 +1,5 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { this.emitWarning(new Error("this is a warning")); this.emitError(new Error("this is an error")); return source; diff --git a/test/fixtures/errors/identity-loader.js b/test/fixtures/errors/identity-loader.js index 6e64f4af6bb..c6d8a635121 100644 --- a/test/fixtures/errors/identity-loader.js +++ b/test/fixtures/errors/identity-loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { return source; }; diff --git a/test/fixtures/errors/irregular-error-loader.js b/test/fixtures/errors/irregular-error-loader.js index 8b38ff7eff0..6ed0ba935ef 100644 --- a/test/fixtures/errors/irregular-error-loader.js +++ b/test/fixtures/errors/irregular-error-loader.js @@ -1,4 +1,5 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { const empty = null; const emptyError = new Error(); this.emitWarning(empty); diff --git a/test/fixtures/errors/no-return-loader.js b/test/fixtures/errors/no-return-loader.js index 0a4b3bfaa71..63c5d351ef1 100644 --- a/test/fixtures/errors/no-return-loader.js +++ b/test/fixtures/errors/no-return-loader.js @@ -1,2 +1,2 @@ -module.exports = function(){ -} +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function () {}; diff --git a/test/fixtures/errors/throw-error-loader.js b/test/fixtures/errors/throw-error-loader.js index 3142eedc09d..59014e2a1b3 100644 --- a/test/fixtures/errors/throw-error-loader.js +++ b/test/fixtures/errors/throw-error-loader.js @@ -1,3 +1,4 @@ -module.exports = function(source) { +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { throw new Error("this is a thrown error"); }; diff --git a/test/hotCases/child-compiler/issue-9706/report-child-assets-loader.js b/test/hotCases/child-compiler/issue-9706/report-child-assets-loader.js index df27ff875b6..95bbe37ed0d 100644 --- a/test/hotCases/child-compiler/issue-9706/report-child-assets-loader.js +++ b/test/hotCases/child-compiler/issue-9706/report-child-assets-loader.js @@ -5,6 +5,7 @@ const { const compilerCache = new WeakMap(); +/** @type {import("../../../../").LoaderDefinition} */ module.exports = function (source) { let childCompiler = compilerCache.get(this._compiler); if (childCompiler === undefined) { diff --git a/test/hotCases/fake-update-loader.js b/test/hotCases/fake-update-loader.js index e2b1884bd74..705d8feedad 100644 --- a/test/hotCases/fake-update-loader.js +++ b/test/hotCases/fake-update-loader.js @@ -1,4 +1,5 @@ -module.exports = function(source) { +/** @type {import("../../").LoaderDefinition<{}, { updateIndex: number }>} */ +module.exports = function (source) { var idx = this.updateIndex; var items = source.split(/---+\r?\n/g); if (items.length > 1) { diff --git a/test/hotCases/loader-import-module/css/loader.js b/test/hotCases/loader-import-module/css/loader.js index 927bbc669c6..c4bf30e37f1 100644 --- a/test/hotCases/loader-import-module/css/loader.js +++ b/test/hotCases/loader-import-module/css/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../").PitchLoaderDefinitionFunction} */ exports.pitch = async function (remaining) { const result = await this.importModule( this.resourcePath + ".webpack[javascript/auto]" + "!=!" + remaining diff --git a/test/hotCases/recover/recover-after-loader-error/loader.js b/test/hotCases/recover/recover-after-loader-error/loader.js index c6713cb9fcb..4f935bbc6ad 100644 --- a/test/hotCases/recover/recover-after-loader-error/loader.js +++ b/test/hotCases/recover/recover-after-loader-error/loader.js @@ -1,5 +1,5 @@ -module.exports = function(source) { - if(source.indexOf("error") >= 0) - throw new Error(source.trim()); +/** @type {import("../../../../").LoaderDefinition} */ +module.exports = function (source) { + if (source.indexOf("error") >= 0) throw new Error(source.trim()); return source; }; diff --git a/test/watchCases/cache/child-compilation-cache/0/report-cache-counters-loader.js b/test/watchCases/cache/child-compilation-cache/0/report-cache-counters-loader.js index 6fc034fe3a0..adedcfa8531 100644 --- a/test/watchCases/cache/child-compilation-cache/0/report-cache-counters-loader.js +++ b/test/watchCases/cache/child-compilation-cache/0/report-cache-counters-loader.js @@ -4,30 +4,38 @@ var cacheMap = new WeakMap(); const getCache = (associate, path) => { let o = cacheMap.get(associate); - if(o === undefined) { + if (o === undefined) { o = new Map(); cacheMap.set(associate, o); } let c = o.get(path); - if(c === undefined) { + if (c === undefined) { c = { counter: 0 }; o.set(path, c); } return c; }; -module.exports = function(source) { - if(map.has(currentWatchStepModule.step)) return map.get(currentWatchStepModule.step); +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (source) { + if (map.has(currentWatchStepModule.step)) + return map.get(currentWatchStepModule.step); - const compilationCache = getCache(this._compiler.root, this._compilation.compilerPath); + const compilationCache = getCache( + this._compiler.root, + this._compilation.compilerPath + ); compilationCache.counter++; - var childCompiler = this._compilation.createChildCompiler("my-compiler " + source.trim(), { - filename: "test" - }); + var childCompiler = this._compilation.createChildCompiler( + "my-compiler " + source.trim(), + { + filename: "test" + } + ); var callback = this.async(); childCompiler.runAsChild((err, entries, compilation) => { - if(err) return callback(err); + if (err) return callback(err); const childCache = getCache(this._compiler.root, compilation.compilerPath); childCache.counter++; diff --git a/test/watchCases/cache/loader-import-module/0/loader.js b/test/watchCases/cache/loader-import-module/0/loader.js index 095a8850439..fde06f26f49 100644 --- a/test/watchCases/cache/loader-import-module/0/loader.js +++ b/test/watchCases/cache/loader-import-module/0/loader.js @@ -1,3 +1,4 @@ +/** @type {import("../../../../../").PitchLoaderDefinitionFunction} */ exports.pitch = async function (remaining) { const result = await this.importModule( `${this.resourcePath}.webpack[javascript/auto]!=!${remaining}` diff --git a/test/watchCases/context/loader-context-dep/0/loader.js b/test/watchCases/context/loader-context-dep/0/loader.js index e81465f2a2a..ed1f2044e2f 100644 --- a/test/watchCases/context/loader-context-dep/0/loader.js +++ b/test/watchCases/context/loader-context-dep/0/loader.js @@ -1,7 +1,8 @@ const path = require("path"); const directory = path.resolve(__dirname, "directory"); -module.exports = function() { +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function () { this.addContextDependency(directory); const callback = this.async(); this.fs.readdir(directory, (err, files) => { diff --git a/test/watchCases/resolve/in-loader/0/loader.js b/test/watchCases/resolve/in-loader/0/loader.js index 51c0656c735..d43844f852c 100644 --- a/test/watchCases/resolve/in-loader/0/loader.js +++ b/test/watchCases/resolve/in-loader/0/loader.js @@ -1,7 +1,9 @@ -module.exports = function() { +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function () { const callback = this.async(); this.resolve(this.context, "./file", (err, file) => { if (err) return callback(err); + if (!file) return callback(new Error("Resolving failed")); this.fs.readFile(file, (err, result) => { if (err) return callback(err); callback( diff --git a/test/watchCases/warnings/warnings-contribute-to-hash/0/warning-loader.js b/test/watchCases/warnings/warnings-contribute-to-hash/0/warning-loader.js index a5206b8bdac..dbf6abe1827 100644 --- a/test/watchCases/warnings/warnings-contribute-to-hash/0/warning-loader.js +++ b/test/watchCases/warnings/warnings-contribute-to-hash/0/warning-loader.js @@ -1,4 +1,5 @@ -module.exports = function(source) { +/** @type {import("../../../../../").LoaderDefinition} */ +module.exports = function (source) { this.emitWarning(new Error(source.trim())); return ""; }; diff --git a/tsconfig.test.json b/tsconfig.test.json index 23a3c6e6f7b..e6e76890abe 100644 --- a/tsconfig.test.json +++ b/tsconfig.test.json @@ -12,5 +12,12 @@ "types": ["node", "jest"], "esModuleInterop": true }, - "include": ["test/**/webpack.config.js", "declarations.test.d.ts"] + "include": [ + "test/**/webpack.config.js", + "test/cases/**/*loader*.js", + "test/watchCases/**/*loader*.js", + "test/configCases/**/*loader*.js", + "test/hotCases/**/*loader*.js", + "declarations.test.d.ts" + ] } diff --git a/types.d.ts b/types.d.ts index 96ae21a2923..6b96379610e 100644 --- a/types.d.ts +++ b/types.d.ts @@ -79,12 +79,8 @@ import { WithStatement, YieldExpression } from "estree"; -import { JSONSchema4, JSONSchema6, JSONSchema7 } from "json-schema"; -import { default as ValidationError } from "schema-utils/declarations/ValidationError"; -import { - Extend, - ValidationErrorConfiguration -} from "schema-utils/declarations/validate"; +import { ValidationError, validate as validateFunction } from "schema-utils"; +import { ValidationErrorConfiguration } from "schema-utils/declarations/validate"; import { AsArray, AsyncParallelHook, @@ -153,6 +149,10 @@ declare class AbstractLibraryPlugin { ): void; static COMMON_LIBRARY_NAME_MESSAGE: string; } +declare interface AdditionalData { + [index: string]: any; + webpackAST: object; +} declare class AggressiveMergingPlugin { constructor(options?: any); options: any; @@ -1650,8 +1650,8 @@ declare class Compilation { */ createChildCompiler( name: string, - outputOptions: OutputNormalized, - plugins: ( + outputOptions?: OutputNormalized, + plugins?: ( | ((this: Compiler, compiler: Compiler) => void) | WebpackPluginInstance )[] @@ -1855,8 +1855,8 @@ declare class Compiler { compilation: Compilation, compilerName: string, compilerIndex: number, - outputOptions: OutputNormalized, - plugins: WebpackPluginInstance[] + outputOptions?: OutputNormalized, + plugins?: WebpackPluginInstance[] ): Compiler; isChild(): boolean; createCompilation(): Compilation; @@ -3035,7 +3035,7 @@ declare class EntryPlugin { * An entry plugin which will handle * creation of the EntryDependency */ - constructor(context: string, entry: string, options: string | EntryOptions); + constructor(context: string, entry: string, options?: string | EntryOptions); context: string; entry: string; options: string | EntryOptions; @@ -4194,7 +4194,7 @@ declare interface HashedModuleIdsPluginOptions { /** * The encoding to use when generating the hash, defaults to 'base64'. All encodings from Node.JS' hash.digest are supported. */ - hashDigest?: "hex" | "latin1" | "base64"; + hashDigest?: "base64" | "latin1" | "hex"; /** * The prefix length of the hash digest to use, defaults to 4. @@ -4217,6 +4217,13 @@ declare class HotModuleReplacementPlugin { apply(compiler: Compiler): void; static getParserHooks(parser: JavascriptParser): HMRJavascriptParserHooks; } + +/** + * These properties are added by the HotModuleReplacementPlugin + */ +declare interface HotModuleReplacementPluginLoaderContext { + hot?: boolean; +} declare class HotUpdateChunk extends Chunk { constructor(); } @@ -4305,6 +4312,17 @@ type IgnorePluginOptions = */ checkResource?: (resource: string, context: string) => boolean; }; +declare interface ImportModuleOptions { + /** + * the target layer + */ + layer?: string; + + /** + * the target public path + */ + publicPath?: string; +} type ImportSource = | undefined | null @@ -5780,12 +5798,45 @@ declare class LoadScriptRuntimeModule extends HelperRuntimeModule { declare interface Loader { [index: string]: any; } +type LoaderContext = NormalModuleLoaderContext & + LoaderRunnerLoaderContext & + LoaderPluginLoaderContext & + HotModuleReplacementPluginLoaderContext; +type LoaderDefinition< + OptionsType = {}, + ContextAdditions = {} +> = LoaderDefinitionFunction & { + raw?: false; + pitch?: PitchLoaderDefinitionFunction; +}; +declare interface LoaderDefinitionFunction< + OptionsType = {}, + ContextAdditions = {} +> { + ( + this: NormalModuleLoaderContext & + LoaderRunnerLoaderContext & + LoaderPluginLoaderContext & + HotModuleReplacementPluginLoaderContext & + ContextAdditions, + content: string, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData + ): string | void | Buffer | Promise; +} declare interface LoaderItem { loader: string; options: any; ident: null | string; type: null | string; } +declare interface LoaderModule { + default?: + | RawLoaderDefinitionFunction + | LoaderDefinitionFunction; + raw?: false; + pitch?: PitchLoaderDefinitionFunction; +} declare class LoaderOptionsPlugin { constructor(options?: LoaderOptionsPluginOptions); options: LoaderOptionsPluginOptions; @@ -5819,6 +5870,165 @@ declare interface LoaderOptionsPluginOptions { context?: string; }; } + +/** + * These properties are added by the LoaderPlugin + */ +declare interface LoaderPluginLoaderContext { + /** + * Resolves the given request to a module, applies all configured loaders and calls + * back with the generated source, the sourceMap and the module instance (usually an + * instance of NormalModule). Use this function if you need to know the source code + * of another module to generate the result. + */ + loadModule( + request: string, + callback: ( + err: null | Error, + source: string, + sourceMap: any, + module: NormalModule + ) => void + ): void; + importModule( + request: string, + options: ImportModuleOptions, + callback: (err?: Error, exports?: any) => any + ): void; + importModule(request: string, options?: ImportModuleOptions): Promise; +} + +/** + * The properties are added by https://github.com/webpack/loader-runner + */ +declare interface LoaderRunnerLoaderContext { + /** + * Add a directory as dependency of the loader result. + */ + addContextDependency(context: string): void; + + /** + * Adds a file as dependency of the loader result in order to make them watchable. + * For example, html-loader uses this technique as it finds src and src-set attributes. + * Then, it sets the url's for those attributes as dependencies of the html file that is parsed. + */ + addDependency(file: string): void; + addMissingDependency(context: string): void; + + /** + * Make this loader async. + */ + async(): ( + err?: null | Error, + content?: string | Buffer, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData + ) => void; + + /** + * Make this loader result cacheable. By default it's cacheable. + * A cacheable loader must have a deterministic result, when inputs and dependencies haven't changed. + * This means the loader shouldn't have other dependencies than specified with this.addDependency. + * Most loaders are deterministic and cacheable. + */ + cacheable(flag?: boolean): void; + callback: ( + err?: null | Error, + content?: string | Buffer, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData + ) => void; + + /** + * Remove all dependencies of the loader result. Even initial dependencies and these of other loaders. + */ + clearDependencies(): void; + + /** + * The directory of the module. Can be used as context for resolving other stuff. + * eg '/workspaces/ts-loader/examples/vanilla/src' + */ + context: string; + readonly currentRequest: string; + readonly data: any; + + /** + * alias of addDependency + * Adds a file as dependency of the loader result in order to make them watchable. + * For example, html-loader uses this technique as it finds src and src-set attributes. + * Then, it sets the url's for those attributes as dependencies of the html file that is parsed. + */ + dependency(file: string): void; + getContextDependencies(): string[]; + getDependencies(): string[]; + getMissingDependencies(): string[]; + + /** + * The index in the loaders array of the current loader. + * In the example: in loader1: 0, in loader2: 1 + */ + loaderIndex: number; + readonly previousRequest: string; + readonly query: string | OptionsType; + readonly remainingRequest: string; + readonly request: string; + + /** + * An array of all the loaders. It is writeable 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: { + request: string; + path: string; + query: string; + fragment: string; + options?: string | object; + ident: string; + normal?: Function; + pitch?: Function; + raw?: boolean; + data?: object; + pitchExecuted: boolean; + normalExecuted: boolean; + }[]; + + /** + * The resource path. + * In the example: "/abc/resource.js" + */ + resourcePath: string; + + /** + * The resource query string. + * Example: "?query" + */ + resourceQuery: string; + + /** + * The resource fragment. + * Example: "#frag" + */ + resourceFragment: string; + + /** + * The resource inclusive query and fragment. + * Example: "/abc/resource.js?query#frag" + */ + resource: string; +} declare class LoaderTargetPlugin { constructor(target: string); target: string; @@ -6888,7 +7098,7 @@ declare class NormalModule extends Module { options: WebpackOptionsNormalized, compilation: Compilation, fs: InputFileSystem - ): any; + ): NormalModuleLoaderContext; getCurrentLoader(loaderContext?: any, index?: any): null | LoaderItem; createSource( context: string, @@ -6964,6 +7174,60 @@ declare abstract class NormalModuleFactory extends ModuleFactory { createGenerator(type?: any, generatorOptions?: object): any; getResolver(type?: any, resolveOptions?: any): ResolverWithOptions; } + +/** + * These properties are added by the NormalModule + */ +declare interface NormalModuleLoaderContext { + version: number; + getOptions(): OptionsType; + getOptions(schema: Parameters[0]): OptionsType; + emitWarning(warning: Error): void; + emitError(error: Error): void; + getLogger(name?: string): WebpackLogger; + resolve( + context: string, + request: string, + callback: ( + arg0: null | Error, + arg1?: string | false, + arg2?: ResolveRequest + ) => void + ): any; + getResolve( + options?: ResolveOptionsWithDependencyType + ): { + ( + context: string, + request: string, + callback: ( + arg0: null | Error, + arg1?: string | false, + arg2?: ResolveRequest + ) => void + ): void; + (context: string, request: string): Promise; + }; + emitFile( + name: string, + content: string, + sourceMap?: string, + assetInfo?: AssetInfo + ): void; + addBuildDependency(dep: string): void; + utils: { + absolutify: (context: string, request: string) => string; + contextify: (context: string, request: string) => string; + }; + rootContext: string; + fs: InputFileSystem; + sourceMap?: boolean; + mode: "development" | "production" | "none"; + webpack?: boolean; + _module?: NormalModule; + _compilation?: Compilation; + _compiler?: Compiler; +} declare class NormalModuleReplacementPlugin { /** * Create an instance of the plugin @@ -8083,6 +8347,21 @@ declare interface PerformanceOptions { */ maxEntrypointSize?: number; } +declare interface PitchLoaderDefinitionFunction< + OptionsType = {}, + ContextAdditions = {} +> { + ( + this: NormalModuleLoaderContext & + LoaderRunnerLoaderContext & + LoaderPluginLoaderContext & + HotModuleReplacementPluginLoaderContext & + ContextAdditions, + remainingRequest: string, + previousRequest: string, + data: object + ): string | void | Buffer | Promise; +} type Plugin = | { apply: (arg0: Resolver) => void } | ((this: Resolver, arg1: Resolver) => void); @@ -8370,6 +8649,28 @@ declare interface RawChunkGroupOptions { preloadOrder?: number; prefetchOrder?: number; } +type RawLoaderDefinition< + OptionsType = {}, + ContextAdditions = {} +> = RawLoaderDefinitionFunction & { + raw: true; + pitch?: PitchLoaderDefinitionFunction; +}; +declare interface RawLoaderDefinitionFunction< + OptionsType = {}, + ContextAdditions = {} +> { + ( + this: NormalModuleLoaderContext & + LoaderRunnerLoaderContext & + LoaderPluginLoaderContext & + HotModuleReplacementPluginLoaderContext & + ContextAdditions, + content: Buffer, + sourceMap?: string | SourceMap, + additionalData?: AdditionalData + ): string | void | Buffer | Promise; +} declare class RawSource extends Source { constructor(source: string | Buffer, convertToString?: boolean); isBuffer(): boolean; @@ -9955,10 +10256,6 @@ declare interface RuntimeValueOptions { buildDependencies?: string[]; version?: string | (() => string); } -type Schema = - | (JSONSchema4 & Extend) - | (JSONSchema6 & Extend) - | (JSONSchema7 & Extend); declare interface ScopeInfo { definitions: StackedMap; topLevelScope: boolean | "arrow"; @@ -10234,6 +10531,15 @@ declare interface SourceData { declare interface SourceLike { source(): string | Buffer; } +declare interface SourceMap { + version: number; + sources: string[]; + mappings: string; + file?: string; + sourceRoot?: string; + sourcesContent?: string[]; + names?: string[]; +} declare class SourceMapDevToolPlugin { constructor(options?: SourceMapDevToolPluginOptions); sourceMapFilename: string | false; @@ -11623,8 +11929,8 @@ declare namespace exports { }; export const validate: (options?: any) => void; export const validateSchema: ( - schema: Schema, - options: object | object[], + schema: Parameters[0], + options: Parameters[1], validationConfiguration?: ValidationErrorConfiguration ) => void; export const version: string; @@ -11750,8 +12056,6 @@ declare namespace exports { Unknown: 3; Used: 4; }>; - export const WebpackOptionsValidationError: ValidationError; - export const ValidationError: ValidationError; export namespace cache { export { MemoryCachePlugin }; } @@ -12010,6 +12314,8 @@ declare namespace exports { WebpackError, WebpackOptionsApply, WebpackOptionsDefaulter, + ValidationError as WebpackOptionsValidationError, + ValidationError, Entry, EntryNormalized, EntryObject, @@ -12042,7 +12348,14 @@ declare namespace exports { StatsModuleReason, StatsModuleTraceDependency, StatsModuleTraceItem, - StatsProfile + StatsProfile, + LoaderModule, + RawLoaderDefinition, + LoaderDefinition, + LoaderDefinitionFunction, + PitchLoaderDefinitionFunction, + RawLoaderDefinitionFunction, + LoaderContext }; } diff --git a/yarn.lock b/yarn.lock index 846a68af651..c7da9f60546 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6267,10 +6267,9 @@ toml@^3.0.0: resolved "https://registry.yarnpkg.com/toml/-/toml-3.0.0.tgz#342160f1af1904ec9d204d03a5d61222d762c5ee" integrity sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w== -tooling@webpack/tooling#v1.18.0: - version "1.18.0" - uid "27496b1099c136e4a8bd69b6d4991c3a493d4a4c" - resolved "https://codeload.github.com/webpack/tooling/tar.gz/27496b1099c136e4a8bd69b6d4991c3a493d4a4c" +tooling@webpack/tooling#v1.19.0: + version "1.19.0" + resolved "https://codeload.github.com/webpack/tooling/tar.gz/6b7567edcd6d93f5e5dc1df8364e0b1204edcac3" dependencies: "@yarnpkg/lockfile" "^1.1.0" ajv "^8.1.0"