webpack/lib/NormalModule.js

1401 lines
41 KiB
JavaScript
Raw Normal View History

2013-01-30 18:49:25 +01:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
2018-07-30 17:08:51 +02:00
2017-02-11 04:16:18 +01:00
"use strict";
2013-01-30 18:49:25 +01:00
2019-11-21 14:36:31 +01:00
const parseJson = require("json-parse-better-errors");
2018-07-30 17:08:51 +02:00
const { getContext, runLoaders } = require("loader-runner");
2019-11-21 14:36:31 +01:00
const querystring = require("querystring");
2020-07-03 14:45:49 +02:00
const { HookMap, SyncHook, AsyncSeriesBailHook } = require("tapable");
const {
CachedSource,
OriginalSource,
RawSource,
SourceMapSource
} = require("webpack-sources");
2018-11-12 14:13:55 +01:00
const Compilation = require("./Compilation");
const HookWebpackError = require("./HookWebpackError");
2017-02-12 14:08:41 +01:00
const Module = require("./Module");
2017-02-11 04:16:18 +01:00
const ModuleBuildError = require("./ModuleBuildError");
const ModuleError = require("./ModuleError");
const ModuleGraphConnection = require("./ModuleGraphConnection");
2018-07-30 17:08:51 +02:00
const ModuleParseError = require("./ModuleParseError");
2017-02-11 04:16:18 +01:00
const ModuleWarning = require("./ModuleWarning");
const RuntimeGlobals = require("./RuntimeGlobals");
2020-07-03 14:45:49 +02:00
const UnhandledSchemeError = require("./UnhandledSchemeError");
2018-07-30 17:08:51 +02:00
const WebpackError = require("./WebpackError");
const formatLocation = require("./formatLocation");
const LazySet = require("./util/LazySet");
const { isSubset } = require("./util/SetHelpers");
const { getScheme } = require("./util/URLAbsoluteSpecifier");
const {
compareLocations,
concatComparators,
compareSelect,
keepOriginalOrder
} = require("./util/comparators");
const createHash = require("./util/createHash");
const { createFakeHook } = require("./util/deprecation");
const { join } = require("./util/fs");
const {
contextify,
absolutify,
makePathsRelative
} = require("./util/identifier");
2018-10-09 14:30:59 +02:00
const makeSerializable = require("./util/makeSerializable");
const memoize = require("./util/memoize");
2017-02-11 04:16:18 +01:00
2018-07-30 17:08:51 +02:00
/** @typedef {import("webpack-sources").Source} Source */
2021-04-20 10:18:59 +02:00
/** @typedef {import("../declarations/LoaderContext").NormalModuleLoaderContext} NormalModuleLoaderContext */
2021-04-16 20:28:30 +02:00
/** @typedef {import("../declarations/WebpackOptions").Mode} Mode */
/** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
/** @typedef {import("./ChunkGraph")} ChunkGraph */
2021-04-16 20:28:30 +02:00
/** @typedef {import("./Compiler")} Compiler */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
2018-07-30 17:08:51 +02:00
/** @typedef {import("./DependencyTemplates")} DependencyTemplates */
2019-11-20 10:58:58 +01:00
/** @typedef {import("./Generator")} Generator */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
2018-07-20 16:24:35 +02:00
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
2018-09-26 09:14:44 +02:00
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./ModuleGraph")} ModuleGraph */
/** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
/** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
/** @typedef {import("./Parser")} Parser */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
2021-04-16 20:28:30 +02:00
/** @typedef {import("./logging/Logger").Logger} WebpackLogger */
2019-07-17 16:02:33 +02:00
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
2018-07-11 13:05:13 +02:00
/**
* @typedef {Object} SourceMap
* @property {number} version
* @property {string[]} sources
* @property {string} mappings
* @property {string=} file
* @property {string=} sourceRoot
* @property {string[]=} sourcesContent
* @property {string[]=} names
*/
2021-04-22 21:43:43 +02:00
const getInvalidDependenciesModuleWarning = memoize(() =>
require("./InvalidDependenciesModuleWarning")
);
const getValidate = memoize(() => require("schema-utils").validate);
const ABSOLUTE_PATH_REGEX = /^([a-zA-Z]:\\|\\\\|\/)/;
/**
* @typedef {Object} LoaderItem
* @property {string} loader
* @property {any} options
* @property {string?} ident
* @property {string?} type
*/
/**
* @param {string} context absolute context path
* @param {string} source a source path
* @param {Object=} associatedObjectForCache an object to which the cache will be attached
* @returns {string} new source path
*/
const contextifySourceUrl = (context, source, associatedObjectForCache) => {
if (source.startsWith("webpack://")) return source;
return `webpack://${makePathsRelative(
context,
source,
associatedObjectForCache
)}`;
};
/**
* @param {string} context absolute context path
* @param {SourceMap} sourceMap a source map
* @param {Object=} associatedObjectForCache an object to which the cache will be attached
* @returns {SourceMap} new source map
*/
const contextifySourceMap = (context, sourceMap, associatedObjectForCache) => {
if (!Array.isArray(sourceMap.sources)) return sourceMap;
const { sourceRoot } = sourceMap;
/** @type {function(string): string} */
const mapper = !sourceRoot
? source => source
: sourceRoot.endsWith("/")
? source =>
source.startsWith("/")
? `${sourceRoot.slice(0, -1)}${source}`
: `${sourceRoot}${source}`
: source =>
source.startsWith("/")
? `${sourceRoot}${source}`
: `${sourceRoot}/${source}`;
const newSources = sourceMap.sources.map(source =>
contextifySourceUrl(context, mapper(source), associatedObjectForCache)
);
return {
...sourceMap,
file: "x",
sourceRoot: undefined,
sources: newSources
};
};
2018-11-07 14:03:25 +01:00
/**
* @param {string | Buffer} input the input
* @returns {string} the converted string
*/
const asString = input => {
if (Buffer.isBuffer(input)) {
return input.toString("utf-8");
}
2018-11-07 14:03:25 +01:00
return input;
2017-11-08 11:32:05 +01:00
};
2018-11-07 14:03:25 +01:00
/**
* @param {string | Buffer} input the input
* @returns {Buffer} the converted buffer
*/
const asBuffer = input => {
if (!Buffer.isBuffer(input)) {
return Buffer.from(input, "utf-8");
2017-10-30 13:56:57 +01:00
}
2018-11-07 14:03:25 +01:00
return input;
2017-10-30 13:56:57 +01:00
};
class NonErrorEmittedError extends WebpackError {
constructor(error) {
super();
this.name = "NonErrorEmittedError";
this.message = "(Emitted value instead of an instance of Error) " + error;
}
}
2018-10-25 10:49:51 +02:00
makeSerializable(
NonErrorEmittedError,
"webpack/lib/NormalModule",
"NonErrorEmittedError"
);
2018-11-12 14:13:55 +01:00
/**
* @typedef {Object} NormalModuleCompilationHooks
2018-12-09 12:54:17 +01:00
* @property {SyncHook<[object, NormalModule]>} loader
2020-10-15 18:21:16 +02:00
* @property {SyncHook<[LoaderItem[], NormalModule, object]>} beforeLoaders
2021-10-18 23:08:24 +02:00
* @property {SyncHook<[NormalModule]>} beforeParse
* @property {SyncHook<[NormalModule]>} beforeSnapshot
2020-07-03 14:45:49 +02:00
* @property {HookMap<AsyncSeriesBailHook<[string, NormalModule], string | Buffer>>} readResourceForScheme
* @property {HookMap<AsyncSeriesBailHook<[object], string | Buffer>>} readResource
* @property {AsyncSeriesBailHook<[NormalModule, NeedBuildContext], boolean>} needBuild
2018-11-12 14:13:55 +01:00
*/
/** @type {WeakMap<Compilation, NormalModuleCompilationHooks>} */
const compilationHooksMap = new WeakMap();
2017-02-11 04:16:18 +01:00
class NormalModule extends Module {
2018-11-12 14:13:55 +01:00
/**
* @param {Compilation} compilation the compilation
* @returns {NormalModuleCompilationHooks} the attached hooks
*/
static getCompilationHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(
"The 'compilation' argument must be an instance of Compilation"
);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks === undefined) {
hooks = {
2020-07-03 14:45:49 +02:00
loader: new SyncHook(["loaderContext", "module"]),
beforeLoaders: new SyncHook(["loaders", "module", "loaderContext"]),
2021-10-18 23:08:24 +02:00
beforeParse: new SyncHook(["module"]),
beforeSnapshot: new SyncHook(["module"]),
// TODO webpack 6 deprecate
readResourceForScheme: new HookMap(scheme => {
const hook = hooks.readResource.for(scheme);
return createFakeHook(
/** @type {AsyncSeriesBailHook<[string, NormalModule], string | Buffer>} */ ({
tap: (options, fn) =>
hook.tap(options, loaderContext =>
fn(loaderContext.resource, loaderContext._module)
),
tapAsync: (options, fn) =>
hook.tapAsync(options, (loaderContext, callback) =>
fn(loaderContext.resource, loaderContext._module, callback)
),
tapPromise: (options, fn) =>
hook.tapPromise(options, loaderContext =>
fn(loaderContext.resource, loaderContext._module)
)
})
);
}),
readResource: new HookMap(
() => new AsyncSeriesBailHook(["loaderContext"])
),
needBuild: new AsyncSeriesBailHook(["module", "context"])
2018-11-12 14:13:55 +01:00
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
2019-11-20 10:58:58 +01:00
/**
* @param {Object} options options object
* @param {string=} options.layer an optional layer in which the module is
2019-11-20 10:58:58 +01:00
* @param {string} options.type module type
* @param {string} options.request request string
2020-03-10 02:59:46 +01:00
* @param {string} options.userRequest request intended by user (without loaders from config)
2019-11-20 10:58:58 +01:00
* @param {string} options.rawRequest request without resolving
* @param {LoaderItem[]} options.loaders list of loaders
2019-11-20 10:58:58 +01:00
* @param {string} options.resource path + query of the real resource
* @param {Record<string, any>=} options.resourceResolveData resource resolve data
2021-08-05 18:47:24 +02:00
* @param {string} options.context context directory for resolving
2020-01-19 09:01:37 +01:00
* @param {string | undefined} options.matchResource path + query of the matched resource (virtual)
* @param {Parser} options.parser the parser used
* @param {object} options.parserOptions the options of the parser used
2019-11-20 10:58:58 +01:00
* @param {Generator} options.generator the generator used
* @param {object} options.generatorOptions the options of the generator used
2019-11-20 10:58:58 +01:00
* @param {Object} options.resolveOptions options used for resolving requests from this module
*/
constructor({
layer,
type,
request,
userRequest,
rawRequest,
loaders,
resource,
resourceResolveData,
2021-08-05 18:47:24 +02:00
context,
matchResource,
parser,
parserOptions,
generator,
generatorOptions,
2020-07-03 14:45:49 +02:00
resolveOptions
}) {
2021-08-05 18:47:24 +02:00
super(type, context || getContext(resource), layer);
// Info from Factory
2018-11-07 14:03:25 +01:00
/** @type {string} */
2017-02-11 04:16:18 +01:00
this.request = request;
2018-11-07 14:03:25 +01:00
/** @type {string} */
2017-02-11 04:16:18 +01:00
this.userRequest = userRequest;
2018-11-07 14:03:25 +01:00
/** @type {string} */
2017-02-11 04:16:18 +01:00
this.rawRequest = rawRequest;
2018-11-07 14:03:25 +01:00
/** @type {boolean} */
this.binary = /^(asset|webassembly)\b/.test(type);
/** @type {Parser} */
2017-02-11 04:16:18 +01:00
this.parser = parser;
this.parserOptions = parserOptions;
2019-11-20 10:58:58 +01:00
/** @type {Generator} */
this.generator = generator;
this.generatorOptions = generatorOptions;
2019-11-20 10:58:58 +01:00
/** @type {string} */
2017-02-11 04:16:18 +01:00
this.resource = resource;
this.resourceResolveData = resourceResolveData;
2019-11-20 10:58:58 +01:00
/** @type {string | undefined} */
this.matchResource = matchResource;
/** @type {LoaderItem[]} */
2017-02-11 04:16:18 +01:00
this.loaders = loaders;
2018-11-07 14:03:25 +01:00
if (resolveOptions !== undefined) {
2019-11-20 10:58:58 +01:00
// already declared in super class
2018-11-07 14:03:25 +01:00
this.resolveOptions = resolveOptions;
}
// Info from Build
2018-11-07 14:03:25 +01:00
/** @type {WebpackError=} */
2017-02-11 04:16:18 +01:00
this.error = null;
2018-11-07 14:03:25 +01:00
/** @private @type {Source=} */
2017-02-11 04:16:18 +01:00
this._source = null;
/** @private @type {Map<string, number> | undefined} **/
this._sourceSizes = undefined;
2021-05-18 16:54:16 +02:00
/** @private @type {Set<string>} */
this._sourceTypes = undefined;
2017-12-06 17:26:02 +01:00
// Cache
this._lastSuccessfulBuildMeta = {};
this._forceBuild = true;
this._isEvaluatingSideEffects = false;
/** @type {WeakSet<ModuleGraph> | undefined} */
this._addedSideEffectsBailout = undefined;
2017-02-11 04:16:18 +01:00
}
/**
* @returns {string} a unique identifier of the module
*/
2017-02-11 04:16:18 +01:00
identifier() {
if (this.layer === null) {
if (this.type === "javascript/auto") {
return this.request;
} else {
return `${this.type}|${this.request}`;
}
} else {
return `${this.type}|${this.request}|${this.layer}`;
}
2017-02-11 04:16:18 +01:00
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
2017-02-11 04:16:18 +01:00
readableIdentifier(requestShortener) {
return requestShortener.shorten(this.userRequest);
}
2018-07-20 16:24:35 +02:00
/**
* @param {LibIdentOptions} options options
* @returns {string | null} an identifier for library inclusion
*/
2017-02-11 04:16:18 +01:00
libIdent(options) {
2019-01-19 13:12:43 +01:00
return contextify(
options.context,
this.userRequest,
options.associatedObjectForCache
);
2017-02-11 04:16:18 +01:00
}
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
*/
2017-02-11 04:16:18 +01:00
nameForCondition() {
const resource = this.matchResource || this.resource;
const idx = resource.indexOf("?");
if (idx >= 0) return resource.substr(0, idx);
return resource;
2017-02-11 04:16:18 +01:00
}
2013-01-30 18:49:25 +01:00
/**
* Assuming this module is in the cache. Update the (cached) module with
* the fresh module from the factory. Usually updates internal references
* and properties.
* @param {Module} module fresh module
* @returns {void}
*/
2018-03-28 16:19:15 +02:00
updateCacheModule(module) {
2018-10-09 14:30:59 +02:00
super.updateCacheModule(module);
const m = /** @type {NormalModule} */ (module);
2020-07-03 14:45:49 +02:00
this.binary = m.binary;
this.request = m.request;
this.userRequest = m.userRequest;
this.rawRequest = m.rawRequest;
this.parser = m.parser;
this.parserOptions = m.parserOptions;
this.generator = m.generator;
this.generatorOptions = m.generatorOptions;
this.resource = m.resource;
this.resourceResolveData = m.resourceResolveData;
2021-08-05 18:47:24 +02:00
this.context = m.context;
this.matchResource = m.matchResource;
this.loaders = m.loaders;
2018-03-28 16:19:15 +02:00
}
/**
* Assuming this module is in the cache. Remove internal references to allow freeing some memory.
*/
cleanupForCache() {
// Make sure to cache types and sizes before cleanup when this module has been built
// They are accessed by the stats and we don't want them to crash after cleanup
// TODO reconsider this for webpack 6
if (this.buildInfo) {
if (this._sourceTypes === undefined) this.getSourceTypes();
for (const type of this._sourceTypes) {
this.size(type);
}
2021-05-18 16:54:16 +02:00
}
super.cleanupForCache();
this.parser = undefined;
this.parserOptions = undefined;
this.generator = undefined;
this.generatorOptions = undefined;
}
/**
* Module should be unsafe cached. Get data that's needed for that.
* This data will be passed to restoreFromUnsafeCache later.
* @returns {object} cached data
*/
getUnsafeCacheData() {
const data = super.getUnsafeCacheData();
data.parserOptions = this.parserOptions;
data.generatorOptions = this.generatorOptions;
return data;
}
restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
this._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
}
/**
* restore unsafe cache data
* @param {object} unsafeCacheData data from getUnsafeCacheData
* @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
*/
_restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
super._restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory);
this.parserOptions = unsafeCacheData.parserOptions;
this.parser = normalModuleFactory.getParser(this.type, this.parserOptions);
this.generatorOptions = unsafeCacheData.generatorOptions;
this.generator = normalModuleFactory.getGenerator(
this.type,
this.generatorOptions
);
2021-05-18 16:54:16 +02:00
// we assume the generator behaves identically and keep cached sourceTypes/Sizes
}
2018-11-07 14:03:25 +01:00
/**
* @param {string} context the compilation context
2018-11-07 14:03:25 +01:00
* @param {string} name the asset name
* @param {string} content the content
* @param {string | TODO} sourceMap an optional source map
* @param {Object=} associatedObjectForCache object for caching
2018-11-07 14:03:25 +01:00
* @returns {Source} the created source
*/
createSourceForAsset(
context,
name,
content,
sourceMap,
associatedObjectForCache
) {
if (sourceMap) {
if (
typeof sourceMap === "string" &&
(this.useSourceMap || this.useSimpleSourceMap)
) {
return new OriginalSource(
content,
contextifySourceUrl(context, sourceMap, associatedObjectForCache)
);
}
if (this.useSourceMap) {
return new SourceMapSource(
content,
name,
contextifySourceMap(context, sourceMap, associatedObjectForCache)
);
}
}
return new RawSource(content);
}
/**
* @param {ResolverWithOptions} resolver a resolver
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {InputFileSystem} fs file system from reading
2021-10-18 23:08:24 +02:00
* @param {NormalModuleCompilationHooks} hooks the hooks
2021-04-20 10:18:59 +02:00
* @returns {NormalModuleLoaderContext} loader context
*/
2021-10-18 23:08:24 +02:00
_createLoaderContext(resolver, options, compilation, fs, hooks) {
2020-02-07 22:38:53 +01:00
const { requestShortener } = compilation.runtimeTemplate;
const getCurrentLoaderName = () => {
const currentLoader = this.getCurrentLoader(loaderContext);
if (!currentLoader) return "(not in loader scope)";
return requestShortener.shorten(currentLoader.loader);
};
const getResolveContext = () => {
return {
fileDependencies: {
add: d => loaderContext.addDependency(d)
},
contextDependencies: {
add: d => loaderContext.addContextDependency(d)
},
missingDependencies: {
add: d => loaderContext.addMissingDependency(d)
}
};
};
const getAbsolutify = memoize(() =>
absolutify.bindCache(compilation.compiler.root)
);
const getAbsolutifyInContext = memoize(() =>
absolutify.bindContextCache(this.context, compilation.compiler.root)
);
const getContextify = memoize(() =>
contextify.bindCache(compilation.compiler.root)
);
const getContextifyInContext = memoize(() =>
contextify.bindContextCache(this.context, compilation.compiler.root)
);
const utils = {
absolutify: (context, request) => {
return context === this.context
? getAbsolutifyInContext()(request)
: getAbsolutify()(context, request);
},
contextify: (context, request) => {
return context === this.context
? getContextifyInContext()(request)
: getContextify()(context, request);
},
createHash
};
2017-02-11 04:16:18 +01:00
const loaderContext = {
version: 2,
getOptions: schema => {
const loader = this.getCurrentLoader(loaderContext);
2019-11-21 14:36:31 +01:00
let { options } = loader;
2019-11-21 14:36:31 +01:00
if (typeof options === "string") {
if (options.substr(0, 1) === "{" && options.substr(-1) === "}") {
2019-11-21 14:36:31 +01:00
try {
options = parseJson(options);
2019-11-21 14:36:31 +01:00
} catch (e) {
throw new Error(`Cannot parse string options: ${e.message}`);
2019-11-21 14:36:31 +01:00
}
} else {
options = querystring.parse(options, "&", "=", {
maxKeys: 0
});
2019-11-21 14:36:31 +01:00
}
}
if (options === null || options === undefined) {
options = {};
2019-11-21 14:36:31 +01:00
}
if (schema) {
let name = "Loader";
let baseDataPath = "options";
let match;
if (schema.title && (match = /^(.+) (.+)$/.exec(schema.title))) {
[, name, baseDataPath] = match;
}
getValidate()(schema, options, {
name,
baseDataPath
});
}
2019-11-21 14:36:31 +01:00
return options;
},
2018-02-25 02:00:20 +01:00
emitWarning: warning => {
if (!(warning instanceof Error)) {
warning = new NonErrorEmittedError(warning);
}
this.addWarning(
new ModuleWarning(warning, {
from: getCurrentLoaderName()
2018-03-02 10:57:46 +01:00
})
);
2017-02-11 04:16:18 +01:00
},
2018-02-25 02:00:20 +01:00
emitError: error => {
if (!(error instanceof Error)) {
error = new NonErrorEmittedError(error);
}
this.addError(
new ModuleError(error, {
from: getCurrentLoaderName()
2018-03-02 10:57:46 +01:00
})
);
2017-02-11 04:16:18 +01:00
},
getLogger: name => {
const currentLoader = this.getCurrentLoader(loaderContext);
return compilation.getLogger(() =>
[currentLoader && currentLoader.loader, name, this.identifier()]
.filter(Boolean)
2019-07-23 09:28:06 +02:00
.join("|")
);
},
2017-02-12 14:08:41 +01:00
resolve(context, request, callback) {
resolver.resolve({}, context, request, getResolveContext(), callback);
2017-02-11 04:16:18 +01:00
},
getResolve(options) {
const child = options ? resolver.withOptions(options) : resolver;
return (context, request, callback) => {
if (callback) {
child.resolve({}, context, request, getResolveContext(), callback);
} else {
return new Promise((resolve, reject) => {
child.resolve(
{},
context,
request,
getResolveContext(),
(err, result) => {
if (err) reject(err);
else resolve(result);
}
);
});
}
};
},
emitFile: (name, content, sourceMap, assetInfo) => {
if (!this.buildInfo.assets) {
this.buildInfo.assets = Object.create(null);
this.buildInfo.assetsInfo = new Map();
}
2018-02-25 02:00:20 +01:00
this.buildInfo.assets[name] = this.createSourceForAsset(
options.context,
2018-02-25 02:00:20 +01:00
name,
content,
sourceMap,
compilation.compiler.root
2018-02-25 02:00:20 +01:00
);
this.buildInfo.assetsInfo.set(name, assetInfo);
},
addBuildDependency: dep => {
if (this.buildInfo.buildDependencies === undefined) {
this.buildInfo.buildDependencies = new LazySet();
}
this.buildInfo.buildDependencies.add(dep);
},
utils,
rootContext: options.context,
webpack: true,
sourceMap: !!this.useSourceMap,
mode: options.mode || "production",
_module: this,
_compilation: compilation,
_compiler: compilation.compiler,
2018-02-25 02:00:20 +01:00
fs: fs
2017-02-11 04:16:18 +01:00
};
Object.assign(loaderContext, options.loader);
2021-10-18 23:08:24 +02:00
hooks.loader.call(loaderContext, this);
2018-11-12 14:13:55 +01:00
return loaderContext;
}
getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
2018-03-02 10:57:46 +01:00
if (
this.loaders &&
this.loaders.length &&
index < this.loaders.length &&
index >= 0 &&
this.loaders[index]
2018-03-02 10:57:46 +01:00
) {
return this.loaders[index];
2018-03-02 10:57:46 +01:00
}
return null;
}
2018-11-07 14:03:25 +01:00
/**
* @param {string} context the compilation context
2018-11-07 14:03:25 +01:00
* @param {string | Buffer} content the content
* @param {string | TODO} sourceMap an optional source map
* @param {Object=} associatedObjectForCache object for caching
2018-11-07 14:03:25 +01:00
* @returns {Source} the created source
*/
createSource(context, content, sourceMap, associatedObjectForCache) {
2018-11-07 14:03:25 +01:00
if (Buffer.isBuffer(content)) {
return new RawSource(content);
}
// if there is no identifier return raw source
2018-02-25 02:00:20 +01:00
if (!this.identifier) {
2018-11-07 14:03:25 +01:00
return new RawSource(content);
}
// from here on we assume we have an identifier
const identifier = this.identifier();
2018-02-25 02:00:20 +01:00
if (this.useSourceMap && sourceMap) {
return new SourceMapSource(
content,
contextifySourceUrl(context, identifier, associatedObjectForCache),
contextifySourceMap(context, sourceMap, associatedObjectForCache)
);
}
if (this.useSourceMap || this.useSimpleSourceMap) {
return new OriginalSource(
content,
contextifySourceUrl(context, identifier, associatedObjectForCache)
);
}
return new RawSource(content);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
2021-10-18 23:08:24 +02:00
* @param {NormalModuleCompilationHooks} hooks the hooks
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
2021-10-18 23:08:24 +02:00
_doBuild(options, compilation, resolver, fs, hooks, callback) {
const loaderContext = this._createLoaderContext(
2018-02-25 02:00:20 +01:00
resolver,
options,
compilation,
2021-10-18 23:08:24 +02:00
fs,
hooks
2018-02-25 02:00:20 +01:00
);
const processResult = (err, result) => {
if (err) {
if (!(err instanceof Error)) {
err = new NonErrorEmittedError(err);
}
const currentLoader = this.getCurrentLoader(loaderContext);
const error = new ModuleBuildError(err, {
from:
currentLoader &&
compilation.runtimeTemplate.requestShortener.shorten(
currentLoader.loader
)
});
return callback(error);
}
const source = result[0];
const sourceMap = result.length >= 1 ? result[1] : null;
const extraInfo = result.length >= 2 ? result[2] : null;
if (!Buffer.isBuffer(source) && typeof source !== "string") {
const currentLoader = this.getCurrentLoader(loaderContext, 0);
const err = new Error(
`Final loader (${
currentLoader
? compilation.runtimeTemplate.requestShortener.shorten(
currentLoader.loader
)
: "unknown"
}) didn't return a Buffer or String`
);
const error = new ModuleBuildError(err);
return callback(error);
}
this._source = this.createSource(
options.context,
this.binary ? asBuffer(source) : asString(source),
sourceMap,
compilation.compiler.root
);
if (this._sourceSizes !== undefined) this._sourceSizes.clear();
this._ast =
typeof extraInfo === "object" &&
extraInfo !== null &&
extraInfo.webpackAST !== undefined
? extraInfo.webpackAST
: null;
return callback();
};
this.buildInfo.fileDependencies = new LazySet();
this.buildInfo.contextDependencies = new LazySet();
this.buildInfo.missingDependencies = new LazySet();
this.buildInfo.cacheable = true;
try {
hooks.beforeLoaders.call(this.loaders, this, loaderContext);
} catch (err) {
processResult(err);
return;
}
if (this.loaders.length > 0) {
this.buildInfo.buildDependencies = new LazySet();
}
2018-02-25 02:00:20 +01:00
runLoaders(
{
resource: this.resource,
loaders: this.loaders,
context: loaderContext,
processResource: (loaderContext, resourcePath, callback) => {
const resource = loaderContext.resource;
2020-07-03 14:45:49 +02:00
const scheme = getScheme(resource);
hooks.readResource
.for(scheme)
.callAsync(loaderContext, (err, result) => {
if (err) return callback(err);
if (typeof result !== "string" && !result) {
return callback(new UnhandledSchemeError(scheme, resource));
}
return callback(null, result);
});
2020-07-03 14:45:49 +02:00
}
2018-02-25 02:00:20 +01:00
},
(err, result) => {
// Cleanup loaderContext to avoid leaking memory in ICs
2021-05-11 09:31:46 +02:00
loaderContext._compilation =
loaderContext._compiler =
loaderContext._module =
loaderContext.fs =
undefined;
if (!result) {
this.buildInfo.cacheable = false;
return processResult(
err || new Error("No result from loader-runner processing"),
null
2018-02-25 02:00:20 +01:00
);
}
this.buildInfo.fileDependencies.addAll(result.fileDependencies);
this.buildInfo.contextDependencies.addAll(result.contextDependencies);
this.buildInfo.missingDependencies.addAll(result.missingDependencies);
for (const loader of this.loaders) {
this.buildInfo.buildDependencies.add(loader.loader);
2018-02-25 02:00:20 +01:00
}
this.buildInfo.cacheable = this.buildInfo.cacheable && result.cacheable;
processResult(err, result.result);
2017-02-11 04:16:18 +01:00
}
2018-02-25 02:00:20 +01:00
);
}
2015-07-13 00:20:09 +02:00
2018-11-07 14:03:25 +01:00
/**
* @param {WebpackError} error the error
* @returns {void}
*/
markModuleAsErrored(error) {
2018-02-26 03:48:51 +01:00
// Restore build meta from successful build to keep importing state
this.buildMeta = { ...this._lastSuccessfulBuildMeta };
this.error = error;
this.addError(error);
}
applyNoParseRule(rule, content) {
2017-02-11 06:59:58 +01:00
// must start with "rule" if rule is a string
2018-02-25 02:00:20 +01:00
if (typeof rule === "string") {
2020-01-19 08:59:39 +01:00
return content.startsWith(rule);
2017-02-11 06:59:58 +01:00
}
2017-06-03 02:28:54 +02:00
2018-02-25 02:00:20 +01:00
if (typeof rule === "function") {
2017-06-03 02:28:54 +02:00
return rule(content);
}
2017-02-11 06:59:58 +01:00
// we assume rule is a regexp
return rule.test(content);
2017-02-11 06:59:58 +01:00
}
// check if module should not be parsed
// returns "true" if the module should !not! be parsed
// returns "false" if the module !must! be parsed
2017-02-15 22:01:09 +01:00
shouldPreventParsing(noParseRule, request) {
2017-02-11 06:59:58 +01:00
// if no noParseRule exists, return false
// the module !must! be parsed.
2018-02-25 02:00:20 +01:00
if (!noParseRule) {
2017-02-11 06:59:58 +01:00
return false;
}
// we only have one rule to check
2018-02-25 02:00:20 +01:00
if (!Array.isArray(noParseRule)) {
2017-02-11 06:59:58 +01:00
// returns "true" if the module is !not! to be parsed
return this.applyNoParseRule(noParseRule, request);
}
2018-02-25 02:00:20 +01:00
for (let i = 0; i < noParseRule.length; i++) {
2017-02-11 06:59:58 +01:00
const rule = noParseRule[i];
// early exit on first truthy match
// this module is !not! to be parsed
2018-02-25 02:00:20 +01:00
if (this.applyNoParseRule(rule, request)) {
2017-02-11 06:59:58 +01:00
return true;
}
}
// no match found, so this module !should! be parsed
return false;
}
_initBuildHash(compilation) {
const hash = createHash(compilation.outputOptions.hashFunction);
if (this._source) {
hash.update("source");
2020-08-02 20:09:36 +02:00
this._source.updateHash(hash);
}
hash.update("meta");
hash.update(JSON.stringify(this.buildMeta));
2019-07-17 16:02:33 +02:00
this.buildInfo.hash = /** @type {string} */ (hash.digest("hex"));
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {function(WebpackError=): void} callback callback function
* @returns {void}
*/
2017-02-11 04:16:18 +01:00
build(options, compilation, resolver, fs, callback) {
this._forceBuild = false;
2017-02-11 04:16:18 +01:00
this._source = null;
if (this._sourceSizes !== undefined) this._sourceSizes.clear();
2021-05-18 16:54:16 +02:00
this._sourceTypes = undefined;
2017-11-03 11:12:45 +01:00
this._ast = null;
2017-02-11 04:16:18 +01:00
this.error = null;
this.clearWarningsAndErrors();
this.clearDependenciesAndBlocks();
this.buildMeta = {};
this.buildInfo = {
cacheable: false,
2018-11-16 18:18:44 +01:00
parsed: true,
fileDependencies: undefined,
contextDependencies: undefined,
missingDependencies: undefined,
buildDependencies: undefined,
valueDependencies: undefined,
hash: undefined,
assets: undefined,
assetsInfo: undefined
};
const startTime = compilation.compiler.fsStartTime || Date.now();
2021-10-18 23:08:24 +02:00
const hooks = NormalModule.getCompilationHooks(compilation);
return this._doBuild(options, compilation, resolver, fs, hooks, err => {
2017-02-11 06:59:58 +01:00
// if we have an error mark module as failed and exit
2018-02-25 02:00:20 +01:00
if (err) {
this.markModuleAsErrored(err);
this._initBuildHash(compilation);
return callback();
}
2017-02-11 06:59:58 +01:00
const handleParseError = e => {
const source = this._source.source();
2019-06-03 15:23:13 +02:00
const loaders = this.loaders.map(item =>
2020-01-14 23:14:47 +01:00
contextify(options.context, item.loader, compilation.compiler.root)
2019-06-03 15:23:13 +02:00
);
const error = new ModuleParseError(source, e, loaders, this.type);
this.markModuleAsErrored(error);
this._initBuildHash(compilation);
return callback();
};
const handleParseResult = result => {
this.dependencies.sort(
concatComparators(
compareSelect(a => a.loc, compareLocations),
keepOriginalOrder(this.dependencies)
)
);
this._initBuildHash(compilation);
this._lastSuccessfulBuildMeta = this.buildMeta;
return handleBuildDone();
};
const handleBuildDone = () => {
2021-10-18 23:08:24 +02:00
try {
hooks.beforeSnapshot.call(this);
} catch (err) {
this.markModuleAsErrored(err);
return callback();
}
const snapshotOptions = compilation.options.snapshot.module;
if (!this.buildInfo.cacheable || !snapshotOptions) {
return callback();
}
// add warning for all non-absolute paths in fileDependencies, etc
// This makes it easier to find problems with watching and/or caching
let nonAbsoluteDependencies = undefined;
const checkDependencies = deps => {
for (const dep of deps) {
if (!ABSOLUTE_PATH_REGEX.test(dep)) {
if (nonAbsoluteDependencies === undefined)
nonAbsoluteDependencies = new Set();
nonAbsoluteDependencies.add(dep);
deps.delete(dep);
try {
const depWithoutGlob = dep.replace(/[\\/]?\*.*$/, "");
const absolute = join(
compilation.fileSystemInfo.fs,
this.context,
depWithoutGlob
);
if (absolute !== dep && ABSOLUTE_PATH_REGEX.test(absolute)) {
(depWithoutGlob !== dep
? this.buildInfo.contextDependencies
: deps
).add(absolute);
}
} catch (e) {
// ignore
}
}
}
};
checkDependencies(this.buildInfo.fileDependencies);
checkDependencies(this.buildInfo.missingDependencies);
checkDependencies(this.buildInfo.contextDependencies);
if (nonAbsoluteDependencies !== undefined) {
2021-05-11 09:31:46 +02:00
const InvalidDependenciesModuleWarning =
getInvalidDependenciesModuleWarning();
this.addWarning(
new InvalidDependenciesModuleWarning(this, nonAbsoluteDependencies)
);
}
// convert file/context/missingDependencies into filesystem snapshot
compilation.fileSystemInfo.createSnapshot(
startTime,
this.buildInfo.fileDependencies,
this.buildInfo.contextDependencies,
this.buildInfo.missingDependencies,
snapshotOptions,
(err, snapshot) => {
if (err) {
this.markModuleAsErrored(err);
return;
}
this.buildInfo.fileDependencies = undefined;
this.buildInfo.contextDependencies = undefined;
this.buildInfo.missingDependencies = undefined;
this.buildInfo.snapshot = snapshot;
return callback();
}
);
};
2021-10-18 23:08:24 +02:00
try {
hooks.beforeParse.call(this);
} catch (err) {
this.markModuleAsErrored(err);
this._initBuildHash(compilation);
return callback();
}
// check if this module should !not! be parsed.
// if so, exit here;
const noParseRule = options.module && options.module.noParse;
if (this.shouldPreventParsing(noParseRule, this.request)) {
// We assume that we need module and exports
this.buildInfo.parsed = false;
this._initBuildHash(compilation);
return handleBuildDone();
}
let result;
2017-02-11 04:16:18 +01:00
try {
const source = this._source.source();
result = this.parser.parse(this._ast || source, {
source,
current: this,
module: this,
compilation: compilation,
options: options
});
2018-02-25 02:00:20 +01:00
} catch (e) {
handleParseError(e);
return;
2017-02-11 04:16:18 +01:00
}
handleParseResult(result);
2015-07-13 00:20:09 +02:00
});
2013-01-30 18:49:25 +01:00
}
2015-07-13 00:20:09 +02:00
/**
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
*/
getConcatenationBailoutReason(context) {
return this.generator.getConcatenationBailoutReason(this, context);
}
/**
* @param {ModuleGraph} moduleGraph the module graph
* @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
*/
getSideEffectsConnectionState(moduleGraph) {
if (this.factoryMeta !== undefined) {
if (this.factoryMeta.sideEffectFree) return false;
if (this.factoryMeta.sideEffectFree === false) return true;
}
if (this.buildMeta !== undefined && this.buildMeta.sideEffectFree) {
if (this._isEvaluatingSideEffects)
return ModuleGraphConnection.CIRCULAR_CONNECTION;
this._isEvaluatingSideEffects = true;
/** @type {ConnectionState} */
let current = false;
for (const dep of this.dependencies) {
const state = dep.getModuleEvaluationSideEffectsState(moduleGraph);
if (state === true) {
if (
this._addedSideEffectsBailout === undefined
? ((this._addedSideEffectsBailout = new WeakSet()), true)
: !this._addedSideEffectsBailout.has(moduleGraph)
) {
this._addedSideEffectsBailout.add(moduleGraph);
moduleGraph
.getOptimizationBailout(this)
.push(
() =>
`Dependency (${
dep.type
}) with side effects at ${formatLocation(dep.loc)}`
);
}
this._isEvaluatingSideEffects = false;
return true;
} else if (state !== ModuleGraphConnection.CIRCULAR_CONNECTION) {
current = ModuleGraphConnection.addConnectionStates(current, state);
}
}
this._isEvaluatingSideEffects = false;
// When caching is implemented here, make sure to not cache when
// at least one circular connection was in the loop above
return current;
} else {
return true;
}
}
/**
2020-03-10 02:59:46 +01:00
* @returns {Set<string>} types available (do not mutate)
*/
getSourceTypes() {
2021-05-18 16:54:16 +02:00
if (this._sourceTypes === undefined) {
this._sourceTypes = this.generator.getTypes(this);
}
return this._sourceTypes;
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({
dependencyTemplates,
runtimeTemplate,
moduleGraph,
chunkGraph,
2020-09-11 09:06:24 +02:00
runtime,
concatenationScope
}) {
/** @type {Set<string>} */
const runtimeRequirements = new Set();
2018-11-16 18:18:44 +01:00
if (!this.buildInfo.parsed) {
runtimeRequirements.add(RuntimeGlobals.module);
runtimeRequirements.add(RuntimeGlobals.exports);
runtimeRequirements.add(RuntimeGlobals.thisAsExports);
2018-11-16 18:18:44 +01:00
}
2020-10-11 01:17:03 +02:00
/** @type {Map<string, any>} */
let data;
const getData = () => {
if (data === undefined) data = new Map();
return data;
};
const sources = new Map();
for (const type of this.generator.getTypes(this)) {
const source = this.error
? new RawSource(
"throw new Error(" + JSON.stringify(this.error.message) + ");"
)
: this.generator.generate(this, {
dependencyTemplates,
runtimeTemplate,
moduleGraph,
chunkGraph,
runtimeRequirements,
runtime,
2020-09-11 09:06:24 +02:00
concatenationScope,
2020-10-11 01:17:03 +02:00
getData,
type
});
2019-11-20 10:48:38 +01:00
if (source) {
sources.set(type, new CachedSource(source));
}
}
/** @type {CodeGenerationResult} */
const resultEntry = {
sources,
2020-10-11 01:17:03 +02:00
runtimeRequirements,
data
};
return resultEntry;
2013-01-30 18:49:25 +01:00
}
/**
* @returns {Source | null} the original source for the module before webpack transformation
*/
originalSource() {
return this._source;
}
/**
* @returns {void}
*/
invalidateBuild() {
this._forceBuild = true;
}
2018-07-25 12:38:34 +02:00
/**
2018-09-26 09:14:44 +02:00
* @param {NeedBuildContext} context context info
* @param {function(WebpackError=, boolean=): void} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
2018-07-25 12:38:34 +02:00
*/
needBuild(context, callback) {
const { fileSystemInfo, compilation, valueCacheVersions } = context;
// build if enforced
2018-09-26 09:14:44 +02:00
if (this._forceBuild) return callback(null, true);
2018-09-26 09:14:44 +02:00
// always try to build in case of an error
if (this.error) return callback(null, true);
2018-09-26 09:14:44 +02:00
// always build when module is not cacheable
if (!this.buildInfo.cacheable) return callback(null, true);
// build when there is no snapshot to check
if (!this.buildInfo.snapshot) return callback(null, true);
// build when valueDependencies have changed
/** @type {Map<string, string | Set<string>>} */
const valueDependencies = this.buildInfo.valueDependencies;
if (valueDependencies) {
if (!valueCacheVersions) return callback(null, true);
for (const [key, value] of valueDependencies) {
if (value === undefined) return callback(null, true);
const current = valueCacheVersions.get(key);
if (
value !== current &&
(typeof value === "string" ||
typeof current === "string" ||
current === undefined ||
!isSubset(value, current))
) {
return callback(null, true);
}
}
}
// check snapshot for validity
fileSystemInfo.checkSnapshotValid(this.buildInfo.snapshot, (err, valid) => {
if (err) return callback(err);
if (!valid) return callback(null, true);
const hooks = NormalModule.getCompilationHooks(compilation);
hooks.needBuild.callAsync(this, context, (err, needBuild) => {
if (err) {
return callback(
HookWebpackError.makeWebpackError(
err,
"NormalModule.getCompilationHooks().needBuild"
)
);
}
callback(null, !!needBuild);
});
});
2017-02-11 04:16:18 +01:00
}
2013-01-30 18:49:25 +01:00
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
const cachedSize =
this._sourceSizes === undefined ? undefined : this._sourceSizes.get(type);
2019-09-25 23:51:38 +02:00
if (cachedSize !== undefined) {
return cachedSize;
2019-09-20 02:44:49 +02:00
}
2019-09-25 23:51:38 +02:00
const size = Math.max(1, this.generator.getSize(this, type));
if (this._sourceSizes === undefined) {
this._sourceSizes = new Map();
}
2019-09-25 23:51:38 +02:00
this._sourceSizes.set(type, size);
return size;
2017-02-11 04:16:18 +01:00
}
/**
* @param {LazySet<string>} fileDependencies set where file dependencies are added to
* @param {LazySet<string>} contextDependencies set where context dependencies are added to
* @param {LazySet<string>} missingDependencies set where missing dependencies are added to
* @param {LazySet<string>} buildDependencies set where build dependencies are added to
*/
addCacheDependencies(
fileDependencies,
contextDependencies,
missingDependencies,
buildDependencies
) {
const { snapshot, buildDependencies: buildDeps } = this.buildInfo;
if (snapshot) {
fileDependencies.addAll(snapshot.getFileIterable());
contextDependencies.addAll(snapshot.getContextIterable());
missingDependencies.addAll(snapshot.getMissingIterable());
} else {
const {
fileDependencies: fileDeps,
contextDependencies: contextDeps,
missingDependencies: missingDeps
} = this.buildInfo;
if (fileDeps !== undefined) fileDependencies.addAll(fileDeps);
if (contextDeps !== undefined) contextDependencies.addAll(contextDeps);
if (missingDeps !== undefined) missingDependencies.addAll(missingDeps);
}
if (buildDeps !== undefined) {
buildDependencies.addAll(buildDeps);
}
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.buildInfo.hash);
2020-07-27 19:36:06 +02:00
this.generator.updateHash(hash, {
module: this,
...context
});
super.updateHash(hash, context);
2017-02-11 04:16:18 +01:00
}
2018-10-09 14:30:59 +02:00
serialize(context) {
const { write } = context;
// deserialize
write(this._source);
write(this.error);
write(this._lastSuccessfulBuildMeta);
write(this._forceBuild);
super.serialize(context);
}
static deserialize(context) {
const obj = new NormalModule({
// will be deserialized by Module
layer: null,
2020-07-03 14:45:49 +02:00
type: "",
// will be filled by updateCacheModule
2020-07-03 14:45:49 +02:00
resource: "",
2021-08-05 18:47:24 +02:00
context: "",
2018-10-09 14:30:59 +02:00
request: null,
userRequest: null,
rawRequest: null,
loaders: null,
matchResource: null,
parser: null,
parserOptions: null,
2018-10-09 14:30:59 +02:00
generator: null,
generatorOptions: null,
2018-10-09 14:30:59 +02:00
resolveOptions: null
});
obj.deserialize(context);
return obj;
}
deserialize(context) {
const { read } = context;
this._source = read();
this.error = read();
this._lastSuccessfulBuildMeta = read();
this._forceBuild = read();
super.deserialize(context);
}
2017-02-11 04:16:18 +01:00
}
2018-10-09 14:30:59 +02:00
makeSerializable(NormalModule, "webpack/lib/NormalModule");
2017-02-11 04:16:18 +01:00
module.exports = NormalModule;