Merge branch 'main' into patch-1

This commit is contained in:
long76 2023-03-25 13:53:20 +03:00 committed by GitHub
commit c5ac0d39c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
94 changed files with 719 additions and 117 deletions

View File

@ -27,7 +27,7 @@ jobs:
node-version: 17.x
cache: "yarn"
- run: yarn --frozen-lockfile
- uses: actions/cache@v1
- uses: actions/cache@v3
with:
path: .eslintcache
key: lint-${{ env.GITHUB_SHA }}
@ -62,7 +62,7 @@ jobs:
- run: yarn --frozen-lockfile
- run: yarn link --frozen-lockfile || true
- run: yarn link webpack --frozen-lockfile
- uses: actions/cache@v1
- uses: actions/cache@v3
with:
path: .jest-cache
key: jest-unit-${{ env.GITHUB_SHA }}
@ -101,7 +101,7 @@ jobs:
- run: yarn --frozen-lockfile
- run: yarn link --frozen-lockfile || true
- run: yarn link webpack --frozen-lockfile
- uses: actions/cache@v2
- uses: actions/cache@v3
with:
path: .jest-cache
key: jest-integration-${{ env.GITHUB_SHA }}

View File

@ -158,11 +158,11 @@ or are automatically applied via regex from your webpack configuration.
#### Transpiling
| Name | Status | Install Size | Description |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: | :------------: | :------------------------------------------------------------------------------------------------ |
| <a href="https://github.com/babel/babel-loader"><img width="48" height="48" title="babel-loader" src="https://worldvectorlogo.com/logos/babel-10.svg"></a> | ![babel-npm] | ![babel-size] | Loads ES2015+ code and transpiles to ES5 using <a href="https://github.com/babel/babel">Babel</a> |
| <a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://cdn.rawgit.com/Microsoft/TypeScript/master/doc/logo.svg"></a> | ![type-npm] | ![type-size] | Loads TypeScript like JavaScript |
| <a href="https://github.com/webpack-contrib/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a> | ![coffee-npm] | ![coffee-size] | Loads CoffeeScript like JavaScript |
| Name | Status | Install Size | Description |
| :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-----------: | :------------: | :------------------------------------------------------------------------------------------------ |
| <a href="https://github.com/babel/babel-loader"><img width="48" height="48" title="babel-loader" src="https://worldvectorlogo.com/logos/babel-10.svg"></a> | ![babel-npm] | ![babel-size] | Loads ES2015+ code and transpiles to ES5 using <a href="https://github.com/babel/babel">Babel</a> |
| <a href="https://github.com/TypeStrong/ts-loader"><img width="48" height="48" src="https://raw.githubusercontent.com/microsoft/TypeScript-Website/f407e1ae19e5e990d9901ac8064a32a8cc60edf0/packages/typescriptlang-org/static/branding/ts-logo-128.svg"></a> | ![type-npm] | ![type-size] | Loads TypeScript like JavaScript |
| <a href="https://github.com/webpack-contrib/coffee-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/coffeescript.svg"></a> | ![coffee-npm] | ![coffee-size] | Loads CoffeeScript like JavaScript |
[babel-npm]: https://img.shields.io/npm/v/babel-loader.svg
[babel-size]: https://packagephobia.com/badge?p=babel-loader
@ -175,7 +175,7 @@ or are automatically applied via regex from your webpack configuration.
| Name | Status | Install Size | Description |
| :-----------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :-------------: | :--------------: | :-------------------------------------------------------------------------------------- |
| <a href="https://github.com/webpack-contrib/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5.svg"></a> | ![html-npm] | ![html-size] | Exports HTML as string, requires references to static resources |
| <a href="https://github.com/webpack-contrib/html-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/html5-2.svg"></a> | ![html-npm] | ![html-size] | Exports HTML as string, requires references to static resources |
| <a href="https://github.com/pugjs/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug-npm] | ![pug-size] | Loads Pug templates and returns a function |
| <a href="https://github.com/webdiscus/pug-loader"><img width="48" height="48" src="https://cdn.rawgit.com/pugjs/pug-logo/master/SVG/pug-final-logo-_-colour-128.svg"></a> | ![pug3-npm] | ![pug3-size] | Compiles Pug to a function or HTML string, useful for use with Vue, React, Angular |
| <a href="https://github.com/peerigon/markdown-loader"><img width="48" height="48" src="https://worldvectorlogo.com/logos/markdown.svg"></a> | ![md-npm] | ![md-size] | Compiles Markdown to HTML |

View File

@ -53,6 +53,19 @@ const isInstalled = packageName => {
}
} while (dir !== (dir = path.dirname(dir)));
// https://github.com/nodejs/node/blob/v18.9.1/lib/internal/modules/cjs/loader.js#L1274
// eslint-disable-next-line no-warning-comments
// @ts-ignore
for (const internalPath of require("module").globalPaths) {
try {
if (fs.statSync(path.join(internalPath, packageName)).isDirectory()) {
return true;
}
} catch (_error) {
// Nothing
}
}
return false;
};

12
declarations.d.ts vendored
View File

@ -246,10 +246,20 @@ declare module "@webassemblyjs/ast" {
declare module "webpack-sources" {
export type MapOptions = { columns?: boolean; module?: boolean };
export type RawSourceMap = {
version: number;
sources: string[];
names: string[];
sourceRoot?: string;
sourcesContent?: string[];
mappings: string;
file: string;
};
export abstract class Source {
size(): number;
map(options?: MapOptions): Object;
map(options?: MapOptions): RawSourceMap | null;
sourceAndMap(options?: MapOptions): {
source: string | Buffer;

View File

@ -212,6 +212,12 @@ export interface LoaderRunnerLoaderContext<OptionsType> {
* Example: "/abc/resource.js?query#frag"
*/
resource: string;
/**
* Target of compilation.
* Example: "web"
*/
target: string;
}
type AdditionalData = {

View File

@ -573,6 +573,10 @@ export type UniqueName = string;
* The filename of WebAssembly modules as relative path inside the 'output.path' directory.
*/
export type WebassemblyModuleFilename = string;
/**
* Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.
*/
export type WorkerPublicPath = string;
/**
* The number of parallel processed modules in the compilation.
*/
@ -2176,6 +2180,10 @@ export interface Output {
* The method of loading chunks (methods included by default are 'jsonp' (web), 'import' (ESM), 'importScripts' (WebWorker), 'require' (sync node.js), 'async-node' (async node.js), but others might be added by plugins).
*/
workerChunkLoading?: ChunkLoading;
/**
* Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.
*/
workerPublicPath?: WorkerPublicPath;
/**
* The method of loading WebAssembly Modules (methods included by default are 'fetch' (web/WebWorker), 'async-node' (node.js), but others might be added by plugins).
*/
@ -3361,6 +3369,10 @@ export interface OutputNormalized {
* The method of loading chunks (methods included by default are 'jsonp' (web), 'import' (ESM), 'importScripts' (WebWorker), 'require' (sync node.js), 'async-node' (async node.js), but others might be added by plugins).
*/
workerChunkLoading?: ChunkLoading;
/**
* Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.
*/
workerPublicPath?: WorkerPublicPath;
/**
* The method of loading WebAssembly Modules (methods included by default are 'fetch' (web/WebWorker), 'async-node' (node.js), but others might be added by plugins).
*/

View File

@ -20,7 +20,7 @@ import("./async2");
```javascript
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
main: "./example"
},

View File

@ -1,6 +1,6 @@
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
main: "./example"
},

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
module: {
rules: [
{

View File

@ -86,7 +86,7 @@ module.exports = function() {
const path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
main: ["./example.js"]
},

View File

@ -2,7 +2,7 @@
const path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
main: ["./example.js"]
},

View File

@ -13,7 +13,7 @@ var path = require("path");
var webpack = require("../../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
context: __dirname,
entry: ["example-vendor"],
output: {

View File

@ -2,7 +2,7 @@ var path = require("path");
var webpack = require("../../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
context: __dirname,
entry: ["example-vendor"],
output: {

View File

@ -10,7 +10,7 @@ This is the _user_ bundle, which uses the manifest from [dll-reference example](
var path = require("path");
var webpack = require("../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname, "..", "dll"),

View File

@ -1,7 +1,7 @@
var path = require("path");
var webpack = require("../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
plugins: [
new webpack.DllReferencePlugin({
context: path.join(__dirname, "..", "dll"),

View File

@ -10,7 +10,7 @@ This is the _reference_ bundle (with the manifests) for [dll user example](https
var path = require("path");
var webpack = require("../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
resolve: {
extensions: [".js", ".jsx"]
},

View File

@ -1,7 +1,7 @@
var path = require("path");
var webpack = require("../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
resolve: {
extensions: [".js", ".jsx"]
},

View File

@ -6,7 +6,7 @@ var webpack = require("../../");
module.exports = [
{
name: "vendor",
// mode: "development || "production",
// mode: "development" || "production",
entry: ["./vendor", "./vendor2"],
output: {
path: path.resolve(__dirname, "dist"),
@ -23,7 +23,7 @@ module.exports = [
{
name: "app",
// mode: "development || "production",
// mode: "development" || "production",
dependencies: ["vendor"],
entry: {
pageA: "./pageA",

View File

@ -3,7 +3,7 @@ var webpack = require("../../");
module.exports = [
{
name: "vendor",
// mode: "development || "production",
// mode: "development" || "production",
entry: ["./vendor", "./vendor2"],
output: {
path: path.resolve(__dirname, "dist"),
@ -20,7 +20,7 @@ module.exports = [
{
name: "app",
// mode: "development || "production",
// mode: "development" || "production",
dependencies: ["vendor"],
entry: {
pageA: "./pageA",

View File

@ -28,7 +28,7 @@ exports.exampleValue = subtract(add(42, 2), 2);
```javascript
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
output: {
libraryTarget: "umd"
},

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
output: {
libraryTarget: "umd"
},

View File

@ -23,7 +23,7 @@ require.ensure(["./a", "./e"], function(require) {
```javascript
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
optimization: {
splitChunks: {
minSize: 0 // This example is too small

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
optimization: {
splitChunks: {
minSize: 0 // This example is too small

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
optimization: {
splitChunks: {
minSize: 0 // This example is too small

View File

@ -3,7 +3,7 @@
```javascript
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: "./example",
output: {
path: path.join(__dirname, "dist"),

View File

@ -1,6 +1,6 @@
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: "./example",
output: {
path: path.join(__dirname, "dist"),

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
optimization: {
concatenateModules: false
}

View File

@ -20,7 +20,7 @@ The backward compatibility (non-HTTP2 client) improves with bigger `maxSize`, as
var path = require("path");
var webpack = require("../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
cache: true, // better performance for the AggressiveSplittingPlugin
entry: "./example",
output: {

View File

@ -1,7 +1,7 @@
var path = require("path");
var webpack = require("../../");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
cache: true, // better performance for the AggressiveSplittingPlugin
entry: "./example",
output: {

View File

@ -3,7 +3,7 @@
```javascript
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
// The entry points for the pages
// They also contains router

View File

@ -1,6 +1,6 @@
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
// The entry points for the pages
// They also contains router

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
module: {
rules: [
{

View File

@ -26,7 +26,7 @@ Note: decreasing `maxInitial/AsyncRequest` will increase duplication further to
```
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
pageA: "./pages/a",
pageB: "./pages/b",

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
pageA: "./pages/a",
pageB: "./pages/b",

View File

@ -15,7 +15,7 @@ var webpack = require("../../");
module.exports = [
{
name: "mobile",
// mode: "development || "production",
// mode: "development" || "production",
entry: "./example",
output: {
path: path.join(__dirname, "dist"),
@ -30,7 +30,7 @@ module.exports = [
{
name: "desktop",
// mode: "development || "production",
// mode: "development" || "production",
entry: "./example",
output: {
path: path.join(__dirname, "dist"),

View File

@ -3,7 +3,7 @@ var webpack = require("../../");
module.exports = [
{
name: "mobile",
// mode: "development || "production",
// mode: "development" || "production",
entry: "./example",
output: {
path: path.join(__dirname, "dist"),
@ -18,7 +18,7 @@ module.exports = [
{
name: "desktop",
// mode: "development || "production",
// mode: "development" || "production",
entry: "./example",
output: {
path: path.join(__dirname, "dist"),

View File

@ -17,7 +17,7 @@ Note: When your library has dependencies that should not be included in the comp
```javascript
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
alpha: "./alpha",
beta: "./beta"

View File

@ -1,6 +1,6 @@
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
alpha: "./alpha",
beta: "./beta"

View File

@ -51,7 +51,7 @@ require.ensure(["./shared"], function(require) {
```javascript
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
pageA: "./pageA",
pageB: "./pageB"

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
pageA: "./pageA",
pageB: "./pageB"

View File

@ -3,7 +3,7 @@
```javascript
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
vendor1: ["./vendor1"],
vendor2: ["./vendor2"],

View File

@ -1,6 +1,6 @@
var path = require("path");
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
entry: {
vendor1: ["./vendor1"],
vendor2: ["./vendor2"],

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
output: {
publicPath: "dist/"
},

View File

@ -1,5 +1,5 @@
module.exports = {
// mode: "development || "production",
// mode: "development" || "production",
output: {
webassemblyModuleFilename: "[hash].wasm",
publicPath: "dist/"

View File

@ -162,6 +162,7 @@ ModuleFilenameHelpers.createFilename = (
resource: resource,
resourcePath: memoize(resourcePath),
absoluteResourcePath: memoize(absoluteResourcePath),
loaders: memoize(loaders),
allLoaders: memoize(allLoaders),
query: memoize(query),
moduleId: memoize(moduleId),

View File

@ -128,6 +128,9 @@ class ModuleGraph {
/** @type {Map<Module, WeakTupleMap<any, any>>} */
this._moduleMemCaches = undefined;
/** @type {string} */
this._cacheStage = undefined;
}
/**

View File

@ -330,6 +330,8 @@ class NormalModule extends Module {
this._isEvaluatingSideEffects = false;
/** @type {WeakSet<ModuleGraph> | undefined} */
this._addedSideEffectsBailout = undefined;
/** @type {Map<string, any>} */
this._codeGeneratorData = new Map();
}
/**
@ -1188,11 +1190,9 @@ class NormalModule extends Module {
runtimeRequirements.add(RuntimeGlobals.thisAsExports);
}
/** @type {Map<string, any>} */
let data;
/** @type {function(): Map<string, any>} */
const getData = () => {
if (data === undefined) data = new Map();
return data;
return this._codeGeneratorData;
};
const sources = new Map();
@ -1223,7 +1223,7 @@ class NormalModule extends Module {
const resultEntry = {
sources,
runtimeRequirements,
data
data: this._codeGeneratorData
};
return resultEntry;
}
@ -1371,6 +1371,7 @@ class NormalModule extends Module {
write(this.error);
write(this._lastSuccessfulBuildMeta);
write(this._forceBuild);
write(this._codeGeneratorData);
super.serialize(context);
}
@ -1403,6 +1404,7 @@ class NormalModule extends Module {
this.error = read();
this._lastSuccessfulBuildMeta = read();
this._forceBuild = read();
this._codeGeneratorData = read();
super.deserialize(context);
}
}

View File

@ -841,10 +841,10 @@ class NormalModuleFactory extends ModuleFactory {
(err2, hints) => {
if (err2) {
err.message += `
An fatal error happened during resolving additional hints for this error: ${err2.message}`;
A fatal error happened during resolving additional hints for this error: ${err2.message}`;
err.stack += `
An fatal error happened during resolving additional hints for this error:
A fatal error happened during resolving additional hints for this error:
${err2.stack}`;
return callback(err);
}

View File

@ -47,13 +47,32 @@ const validate = createSchemaValidation(
* @property {ItemCacheFacade} cacheItem cache item
*/
const METACHARACTERS_REGEXP = /[-[\]\\/{}()*+?.^$|]/g;
const CONTENT_HASH_DETECT_REGEXP = /\[contenthash(:\w+)?\]/;
const CSS_AND_JS_MODULE_EXTENSIONS_REGEXP = /\.((c|m)?js|css)($|\?)/i;
const CSS_EXTENSION_DETECT_REGEXP = /\.css($|\?)/i;
const MAP_URL_COMMENT_REGEXP = /\[map\]/g;
const URL_COMMENT_REGEXP = /\[url\]/g;
const URL_FORMATTING_REGEXP = /^\n\/\/(.*)$/;
/**
* Reset's .lastIndex of stateful Regular Expressions
* For when `test` or `exec` is called on them
* @param {RegExp} regexp Stateful Regular Expression to be reset
* @returns {void}
*
*/
const resetRegexpState = regexp => {
regexp.lastIndex = -1;
};
/**
* Escapes regular expression metacharacters
* @param {string} str String to quote
* @returns {string} Escaped string
*/
const quoteMeta = str => {
return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
return str.replace(METACHARACTERS_REGEXP, "\\$&");
};
/**
@ -152,7 +171,7 @@ class SourceMapDevToolPlugin {
const fallbackModuleFilenameTemplate = this.fallbackModuleFilenameTemplate;
const requestShortener = compiler.requestShortener;
const options = this.options;
options.test = options.test || /\.((c|m)?js|css)($|\?)/i;
options.test = options.test || CSS_AND_JS_MODULE_EXTENSIONS_REGEXP;
const matchObject = ModuleFilenameHelpers.matchObject.bind(
undefined,
@ -409,7 +428,9 @@ class SourceMapDevToolPlugin {
sourceMap.file = file;
const usesContentHash =
sourceMapFilename &&
/\[contenthash(:\w+)?\]/.test(sourceMapFilename);
CONTENT_HASH_DETECT_REGEXP.test(sourceMapFilename);
resetRegexpState(CONTENT_HASH_DETECT_REGEXP);
// If SourceMap and asset uses contenthash, avoid a circular dependency by hiding hash in `file`
if (usesContentHash && task.assetInfo.contenthash) {
@ -428,13 +449,16 @@ class SourceMapDevToolPlugin {
/** @type {string | false} */
let currentSourceMappingURLComment = sourceMappingURLComment;
let cssExtensionDetected =
CSS_EXTENSION_DETECT_REGEXP.test(file);
resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
if (
currentSourceMappingURLComment !== false &&
/\.css($|\?)/i.test(file)
cssExtensionDetected
) {
currentSourceMappingURLComment =
currentSourceMappingURLComment.replace(
/^\n\/\/(.*)$/,
URL_FORMATTING_REGEXP,
"\n/*$1*/"
);
}
@ -516,9 +540,9 @@ class SourceMapDevToolPlugin {
const asset = new ConcatSource(
new RawSource(source),
currentSourceMappingURLComment
.replace(/\[map\]/g, () => sourceMapString)
.replace(MAP_URL_COMMENT_REGEXP, () => sourceMapString)
.replace(
/\[url\]/g,
URL_COMMENT_REGEXP,
() =>
`data:application/json;charset=utf-8;base64,${Buffer.from(
sourceMapString,

View File

@ -391,7 +391,8 @@ class WebpackOptionsApply extends OptionsApply {
new WorkerPlugin(
options.output.workerChunkLoading,
options.output.workerWasmLoading,
options.output.module
options.output.module,
options.output.workerPublicPath
).apply(compiler);
new DefaultStatsFactoryPlugin().apply(compiler);

View File

@ -916,6 +916,7 @@ const applyOutputDefaults = (
? "auto"
: ""
);
D(output, "workerPublicPath", "");
D(output, "chunkLoadTimeout", 120000);
D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4");
D(output, "hashDigest", "hex");

View File

@ -373,6 +373,7 @@ const getNormalizedWebpackOptions = config => {
uniqueName: output.uniqueName,
wasmLoading: output.wasmLoading,
webassemblyModuleFilename: output.webassemblyModuleFilename,
workerPublicPath: output.workerPublicPath,
workerChunkLoading: output.workerChunkLoading,
workerWasmLoading: output.workerWasmLoading
};

View File

@ -64,7 +64,9 @@ class ContainerPlugin {
const { name, exposes, shareScope, filename, library, runtime } =
this._options;
compiler.options.output.enabledLibraryTypes.push(library.type);
if (!compiler.options.output.enabledLibraryTypes.includes(library.type)) {
compiler.options.output.enabledLibraryTypes.push(library.type);
}
compiler.hooks.make.tapAsync(PLUGIN_NAME, (compilation, callback) => {
const dep = new ContainerEntryDependency(name, exposes, shareScope);

View File

@ -25,10 +25,16 @@ class WorkerDependency extends ModuleDependency {
/**
* @param {string} request request
* @param {[number, number]} range range
* @param {Object} workerDependencyOptions options
* @param {string} workerDependencyOptions.publicPath public path for the worker
*/
constructor(request, range) {
constructor(request, range, workerDependencyOptions) {
super(request);
this.range = range;
// If options are updated, don't forget to update the hash and serialization functions
this.options = workerDependencyOptions;
/** Cache the hash */
this._hashUpdate = undefined;
}
/**
@ -48,6 +54,31 @@ class WorkerDependency extends ModuleDependency {
get category() {
return "worker";
}
/**
* Update the hash
* @param {Hash} hash hash to be updated
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
if (this._hashUpdate === undefined) {
this._hashUpdate = JSON.stringify(this.options);
}
hash.update(this._hashUpdate);
}
serialize(context) {
const { write } = context;
write(this.options);
super.serialize(context);
}
deserialize(context) {
const { read } = context;
this.options = read();
super.deserialize(context);
}
}
WorkerDependency.Template = class WorkerDependencyTemplate extends (
@ -69,6 +100,10 @@ WorkerDependency.Template = class WorkerDependencyTemplate extends (
chunkGraph.getBlockChunkGroup(block)
);
const chunk = entrypoint.getEntrypointChunk();
// We use the workerPublicPath option if provided, else we fallback to the RuntimeGlobal publicPath
const workerImportBaseUrl = dep.options.publicPath
? `"${dep.options.publicPath}"`
: RuntimeGlobals.publicPath;
runtimeRequirements.add(RuntimeGlobals.publicPath);
runtimeRequirements.add(RuntimeGlobals.baseURI);
@ -77,7 +112,7 @@ WorkerDependency.Template = class WorkerDependencyTemplate extends (
source.replace(
dep.range[0],
dep.range[1] - 1,
`/* worker import */ ${RuntimeGlobals.publicPath} + ${
`/* worker import */ ${workerImportBaseUrl} + ${
RuntimeGlobals.getChunkScriptFilename
}(${JSON.stringify(chunk.id)}), ${RuntimeGlobals.baseURI}`
);

View File

@ -48,10 +48,11 @@ const DEFAULT_SYNTAX = [
const workerIndexMap = new WeakMap();
class WorkerPlugin {
constructor(chunkLoading, wasmLoading, module) {
constructor(chunkLoading, wasmLoading, module, workerPublicPath) {
this._chunkLoading = chunkLoading;
this._wasmLoading = wasmLoading;
this._module = module;
this._workerPublicPath = workerPublicPath;
}
/**
* Apply the plugin
@ -298,7 +299,9 @@ class WorkerPlugin {
}
});
block.loc = expr.loc;
const dep = new WorkerDependency(url.string, range);
const dep = new WorkerDependency(url.string, range, {
publicPath: this._workerPublicPath
});
dep.loc = expr.loc;
block.addDependency(dep);
parser.state.module.addBlock(block);

View File

@ -11,6 +11,7 @@ const HotUpdateChunk = require("../HotUpdateChunk");
const Template = require("../Template");
const { getAllChunks } = require("../javascript/ChunkHelpers");
const {
chunkHasJs,
getCompilationHooks,
getChunkFilenameTemplate
} = require("../javascript/JavascriptModulesPlugin");
@ -147,7 +148,11 @@ class ModuleChunkFormatPlugin {
undefined
);
for (const chunk of chunks) {
if (loadedChunks.has(chunk)) continue;
if (
loadedChunks.has(chunk) ||
!chunkHasJs(chunk, chunkGraph)
)
continue;
loadedChunks.add(chunk);
startupSource.add(
`import * as __webpack_chunk_${index}__ from ${JSON.stringify(

View File

@ -11,6 +11,7 @@ const ExternalsPlugin = require("../ExternalsPlugin");
const builtins = [
"assert",
"assert/strict",
"async_hooks",
"buffer",
"child_process",
@ -30,6 +31,7 @@ const builtins = [
"http2",
"https",
"inspector",
"inspector/promises",
"module",
"net",
"os",
@ -41,8 +43,10 @@ const builtins = [
"punycode",
"querystring",
"readline",
"readline/promises",
"repl",
"stream",
"stream/consumers",
"stream/promises",
"stream/web",
"string_decoder",

View File

@ -38,10 +38,8 @@ module.exports = ({ colors, appendOnly, stream }) => {
const writeStatusMessage = () => {
if (!currentStatusMessage) return;
const l = stream.columns;
const args = l
? truncateArgs(currentStatusMessage, l - 1)
: currentStatusMessage;
const l = stream.columns || 40;
const args = truncateArgs(currentStatusMessage, l - 1);
const str = args.join(" ");
const coloredStr = `\u001b[1m${str}\u001b[39m\u001b[22m`;
stream.write(`\x1b[2K\r${coloredStr}`);

View File

@ -342,7 +342,6 @@ ${referencingAssets
for (const oldHash of hashesInOrder) {
const assets = hashToAssets.get(oldHash);
assets.sort(comparator);
const hash = createHash(this._hashFunction);
await Promise.all(
assets.map(asset =>
asset.ownHashes.has(oldHash)
@ -363,6 +362,10 @@ ${referencingAssets
});
let newHash = hooks.updateHash.call(assetsContent, oldHash);
if (!newHash) {
const hash = createHash(this._hashFunction);
if (compilation.outputOptions.hashSalt) {
hash.update(compilation.outputOptions.hashSalt);
}
for (const content of assetsContent) {
hash.update(content);
}

View File

@ -43,7 +43,7 @@ class AutoPublicPathRuntimeModule extends RuntimeModule {
"if (!scriptUrl && document) {",
Template.indent([
`if (document.currentScript)`,
Template.indent(`scriptUrl = document.currentScript.src`),
Template.indent(`scriptUrl = document.currentScript.src;`),
"if (!scriptUrl) {",
Template.indent([
'var scripts = document.getElementsByTagName("script");',

View File

@ -146,8 +146,7 @@ class LoadScriptRuntimeModule extends HelperRuntimeModule {
)});`,
"if(prev) return prev(event);"
])
) +
";",
),
`var timeout = setTimeout(onScriptComplete.bind(null, undefined, { type: 'timeout', target: script }), ${loadTimeout});`,
"script.onerror = onScriptComplete.bind(null, script.onerror);",
"script.onload = onScriptComplete.bind(null, script.onload);",

View File

@ -1,6 +1,6 @@
{
"name": "webpack",
"version": "5.75.0",
"version": "5.76.3",
"author": "Tobias Koppers @sokra",
"description": "Packs CommonJs/AMD modules for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand. Support loaders to preprocess files, i.e. json, jsx, es7, css, less, ... and your custom stuff.",
"license": "MIT",
@ -76,7 +76,7 @@
"less": "^4.0.0",
"less-loader": "^8.0.0",
"lint-staged": "^11.0.0",
"loader-utils": "^2.0.0",
"loader-utils": "^2.0.3",
"lodash": "^4.17.19",
"lodash-es": "^4.17.15",
"memfs": "^3.2.0",

File diff suppressed because one or more lines are too long

View File

@ -3259,6 +3259,9 @@
"workerChunkLoading": {
"$ref": "#/definitions/ChunkLoading"
},
"workerPublicPath": {
"$ref": "#/definitions/WorkerPublicPath"
},
"workerWasmLoading": {
"$ref": "#/definitions/WasmLoading"
}
@ -3415,6 +3418,9 @@
"workerChunkLoading": {
"$ref": "#/definitions/ChunkLoading"
},
"workerPublicPath": {
"$ref": "#/definitions/WorkerPublicPath"
},
"workerWasmLoading": {
"$ref": "#/definitions/WasmLoading"
}
@ -5289,6 +5295,10 @@
}
},
"required": ["apply"]
},
"WorkerPublicPath": {
"description": "Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.",
"type": "string"
}
},
"title": "WebpackOptions",

View File

@ -0,0 +1,152 @@
"use strict";
require("./helpers/warmup-webpack");
const path = require("path");
const fs = require("graceful-fs");
const rimraf = require("rimraf");
let fixtureCount = 0;
describe("Compiler (filesystem caching)", () => {
jest.setTimeout(5000);
const tempFixturePath = path.join(
__dirname,
"fixtures",
"temp-filesystem-cache-fixture"
);
function compile(entry, onSuccess, onError) {
const webpack = require("..");
const options = webpack.config.getNormalizedWebpackOptions({});
options.cache = {
type: "filesystem",
cacheDirectory: path.join(tempFixturePath, "cache")
};
options.entry = entry;
options.context = path.join(__dirname, "fixtures");
options.output.path = path.join(tempFixturePath, "dist");
options.output.filename = "bundle.js";
options.output.pathinfo = true;
options.module = {
rules: [
{
test: /\.svg$/,
type: "asset/resource",
use: {
loader: require.resolve("./fixtures/empty-svg-loader")
}
}
]
};
function runCompiler(onSuccess, onError) {
const c = webpack(options);
c.hooks.compilation.tap(
"CompilerCachingTest",
compilation => (compilation.bail = true)
);
c.run((err, stats) => {
if (err) throw err;
expect(typeof stats).toBe("object");
stats = stats.toJson({
modules: true,
reasons: true
});
expect(typeof stats).toBe("object");
expect(stats).toHaveProperty("errors");
expect(Array.isArray(stats.errors)).toBe(true);
if (stats.errors.length > 0) {
onError(new Error(JSON.stringify(stats.errors, null, 4)));
}
c.close(() => {
onSuccess(stats);
});
});
}
runCompiler(onSuccess, onError);
return {
runAgain: runCompiler
};
}
function cleanup() {
rimraf.sync(`${tempFixturePath}*`);
}
beforeAll(cleanup);
afterAll(cleanup);
function createTempFixture() {
const fixturePath = `${tempFixturePath}-${fixtureCount}`;
const usesAssetFilepath = path.join(fixturePath, "uses-asset.js");
const svgFilepath = path.join(fixturePath, "file.svg");
// Remove previous copy if present
rimraf.sync(fixturePath);
// Copy over file since we"ll be modifying some of them
fs.mkdirSync(fixturePath);
fs.copyFileSync(
path.join(__dirname, "fixtures", "uses-asset.js"),
usesAssetFilepath
);
fs.copyFileSync(path.join(__dirname, "fixtures", "file.svg"), svgFilepath);
fixtureCount++;
return {
rootPath: fixturePath,
usesAssetFilepath: usesAssetFilepath,
svgFilepath: svgFilepath
};
}
it("should compile again when cached asset has changed but loader output remains the same", done => {
const tempFixture = createTempFixture();
const onError = error => done(error);
const helper = compile(
tempFixture.usesAssetFilepath,
stats => {
// Not cached the first time
expect(stats.assets[0].name).toBe("bundle.js");
expect(stats.assets[0].emitted).toBe(true);
expect(stats.assets[1].name).toMatch(/\w+\.svg$/);
expect(stats.assets[0].emitted).toBe(true);
helper.runAgain(stats => {
// Cached the second run
expect(stats.assets[0].name).toBe("bundle.js");
expect(stats.assets[0].emitted).toBe(false);
expect(stats.assets[1].name).toMatch(/\w+\.svg$/);
expect(stats.assets[0].emitted).toBe(false);
const svgContent = fs
.readFileSync(tempFixture.svgFilepath)
.toString()
.replace("icon-square-small", "icon-square-smaller");
fs.writeFileSync(tempFixture.svgFilepath, svgContent);
helper.runAgain(stats => {
// Still cached after file modification because loader always returns empty
expect(stats.assets[0].name).toBe("bundle.js");
expect(stats.assets[0].emitted).toBe(false);
expect(stats.assets[1].name).toMatch(/\w+\.svg$/);
expect(stats.assets[0].emitted).toBe(false);
done();
}, onError);
}, onError);
},
onError
);
});
});

View File

@ -360,6 +360,7 @@ describe("snapshots", () => {
"wasmLoading": "fetch",
"webassemblyModuleFilename": "[hash].module.wasm",
"workerChunkLoading": "import-scripts",
"workerPublicPath": "",
"workerWasmLoading": "fetch",
},
"parallelism": 100,
@ -1308,8 +1309,9 @@ describe("snapshots", () => {
+ "wasmLoading": "async-node",
@@ ... @@
- "workerChunkLoading": "import-scripts",
- "workerWasmLoading": "fetch",
+ "workerChunkLoading": "require",
@@ ... @@
- "workerWasmLoading": "fetch",
+ "workerWasmLoading": "async-node",
@@ ... @@
- "aliasFields": Array [
@ -1452,8 +1454,9 @@ describe("snapshots", () => {
+ "wasmLoading": "async-node",
@@ ... @@
- "workerChunkLoading": "import-scripts",
- "workerWasmLoading": "fetch",
+ "workerChunkLoading": "require",
@@ ... @@
- "workerWasmLoading": "fetch",
+ "workerWasmLoading": "async-node",
@@ ... @@
- "aliasFields": Array [
@ -1578,8 +1581,9 @@ describe("snapshots", () => {
+ "wasmLoading": "async-node",
@@ ... @@
- "workerChunkLoading": "import-scripts",
- "workerWasmLoading": "fetch",
+ "workerChunkLoading": "require",
@@ ... @@
- "workerWasmLoading": "fetch",
+ "workerWasmLoading": "async-node",
@@ ... @@
- "aliasFields": Array [

View File

@ -218,7 +218,7 @@ describe("ProgressPlugin", function () {
const logs = getLogs(stderr.toString());
expect(logs.length).toBeGreaterThan(20);
expect(_.maxBy(logs, "length").length).toBeGreaterThan(50);
expect(_.maxBy(logs, "length").length).not.toBeGreaterThan(40);
});
});
@ -242,6 +242,7 @@ describe("ProgressPlugin", function () {
activeModules: true
});
process.stderr.columns = 70;
return RunCompilerAsync(compiler).then(() => {
const logs = stderr.toString();
@ -255,6 +256,7 @@ describe("ProgressPlugin", function () {
it("should get the custom handler text from the log", () => {
const compiler = createSimpleCompilerWithCustomHandler();
process.stderr.columns = 70;
return RunCompilerAsync(compiler).then(() => {
const logs = stderr.toString();
expect(logs).toEqual(

View File

@ -6696,6 +6696,19 @@ Object {
"multiple": false,
"simpleType": "string",
},
"output-worker-public-path": Object {
"configs": Array [
Object {
"description": "Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.",
"multiple": false,
"path": "output.workerPublicPath",
"type": "string",
},
],
"description": "Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.",
"multiple": false,
"simpleType": "string",
},
"output-worker-wasm-loading": Object {
"configs": Array [
Object {

View File

@ -3,12 +3,12 @@
exports[`StatsTestCases should print correct stats for aggressive-splitting-entry 1`] = `
"fitting:
PublicPath: auto
asset fitting-7287b3126510b3ba1197.js 16.1 KiB [emitted] [immutable]
asset fitting-27df06fdbf7adbff38d6.js 16.1 KiB [emitted] [immutable]
asset fitting-50595d23e8f97d7ccd2a.js 1.9 KiB [emitted] [immutable]
asset fitting-5bc77880fdc9e2bf09ee.js 1.9 KiB [emitted] [immutable]
asset fitting-72afdc913f6cf884b457.js 1.08 KiB [emitted] [immutable]
Entrypoint main 19.9 KiB = fitting-50595d23e8f97d7ccd2a.js 1.9 KiB fitting-5bc77880fdc9e2bf09ee.js 1.9 KiB fitting-7287b3126510b3ba1197.js 16.1 KiB
chunk (runtime: main) fitting-7287b3126510b3ba1197.js 1.87 KiB (javascript) 8.65 KiB (runtime) [entry] [rendered]
Entrypoint main 19.9 KiB = fitting-50595d23e8f97d7ccd2a.js 1.9 KiB fitting-5bc77880fdc9e2bf09ee.js 1.9 KiB fitting-27df06fdbf7adbff38d6.js 16.1 KiB
chunk (runtime: main) fitting-27df06fdbf7adbff38d6.js 1.87 KiB (javascript) 8.65 KiB (runtime) [entry] [rendered]
> ./index main
runtime modules 8.65 KiB 11 modules
cacheable modules 1.87 KiB
@ -30,12 +30,12 @@ exports[`StatsTestCases should print correct stats for aggressive-splitting-entr
content-change:
PublicPath: auto
asset content-change-8d02d3f29ce2746961bb.js 16.1 KiB [emitted] [immutable]
asset content-change-ea14516bfb79836da4ae.js 16.1 KiB [emitted] [immutable]
asset content-change-50595d23e8f97d7ccd2a.js 1.9 KiB [emitted] [immutable]
asset content-change-5bc77880fdc9e2bf09ee.js 1.9 KiB [emitted] [immutable]
asset content-change-72afdc913f6cf884b457.js 1.08 KiB [emitted] [immutable]
Entrypoint main 19.9 KiB = content-change-50595d23e8f97d7ccd2a.js 1.9 KiB content-change-5bc77880fdc9e2bf09ee.js 1.9 KiB content-change-8d02d3f29ce2746961bb.js 16.1 KiB
chunk (runtime: main) content-change-8d02d3f29ce2746961bb.js 1.87 KiB (javascript) 8.66 KiB (runtime) [entry] [rendered]
Entrypoint main 19.9 KiB = content-change-50595d23e8f97d7ccd2a.js 1.9 KiB content-change-5bc77880fdc9e2bf09ee.js 1.9 KiB content-change-ea14516bfb79836da4ae.js 16.1 KiB
chunk (runtime: main) content-change-ea14516bfb79836da4ae.js 1.87 KiB (javascript) 8.66 KiB (runtime) [entry] [rendered]
> ./index main
runtime modules 8.66 KiB 11 modules
cacheable modules 1.87 KiB
@ -58,7 +58,7 @@ content-change:
exports[`StatsTestCases should print correct stats for aggressive-splitting-on-demand 1`] = `
"PublicPath: auto
asset 47d8091c27bf6f3a2e25.js 11.6 KiB [emitted] [immutable] (name: main)
asset abdecc928f4f9878244e.js 11.6 KiB [emitted] [immutable] (name: main)
asset 3fc6535262efa7e4fa3b.js 1.91 KiB [emitted] [immutable]
asset 56815935c535fbc0e462.js 1.91 KiB [emitted] [immutable]
asset 2b8c8882bd4326b27013.js 1.9 KiB [emitted] [immutable]
@ -70,12 +70,12 @@ asset f79c60cc3faba968a476.js 1.9 KiB [emitted] [immutable]
asset 7294786e49319a98f5af.js 1010 bytes [emitted] [immutable]
asset c5861419d7f3f6ea6c19.js 1010 bytes [emitted] [immutable]
asset f897ac9956540163d002.js 1010 bytes [emitted] [immutable]
Entrypoint main 11.6 KiB = 47d8091c27bf6f3a2e25.js
Entrypoint main 11.6 KiB = abdecc928f4f9878244e.js
chunk (runtime: main) 5bc77880fdc9e2bf09ee.js 1.76 KiB [rendered] [recorded] aggressive splitted
> ./c ./d ./e ./index.js 3:0-30
./c.js 899 bytes [built] [code generated]
./d.js 899 bytes [built] [code generated]
chunk (runtime: main) 47d8091c27bf6f3a2e25.js (main) 248 bytes (javascript) 6.31 KiB (runtime) [entry] [rendered]
chunk (runtime: main) abdecc928f4f9878244e.js (main) 248 bytes (javascript) 6.31 KiB (runtime) [entry] [rendered]
> ./index main
runtime modules 6.31 KiB 7 modules
./index.js 248 bytes [built] [code generated]
@ -753,8 +753,8 @@ exports[`StatsTestCases should print correct stats for concat-and-sideeffects 1`
`;
exports[`StatsTestCases should print correct stats for context-independence 1`] = `
"asset main-c9ce622840ffef9b8560.js 12.7 KiB [emitted] [immutable] (name: main)
sourceMap main-c9ce622840ffef9b8560.js.map 11 KiB [emitted] [dev] (auxiliary name: main)
"asset main-5fe8293e1c67cc6234cb.js 12.7 KiB [emitted] [immutable] (name: main)
sourceMap main-5fe8293e1c67cc6234cb.js.map 11 KiB [emitted] [dev] (auxiliary name: main)
asset 695-4dd37417c69a0af66bac.js 455 bytes [emitted] [immutable]
sourceMap 695-4dd37417c69a0af66bac.js.map 342 bytes [emitted] [dev]
runtime modules 6.59 KiB 9 modules
@ -769,8 +769,8 @@ built modules 500 bytes [built]
./a/chunk.js + 1 modules (in Xdir/context-independence/a) 66 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms
asset main-c9ce622840ffef9b8560.js 12.7 KiB [emitted] [immutable] (name: main)
sourceMap main-c9ce622840ffef9b8560.js.map 11 KiB [emitted] [dev] (auxiliary name: main)
asset main-5fe8293e1c67cc6234cb.js 12.7 KiB [emitted] [immutable] (name: main)
sourceMap main-5fe8293e1c67cc6234cb.js.map 11 KiB [emitted] [dev] (auxiliary name: main)
asset 695-4dd37417c69a0af66bac.js 455 bytes [emitted] [immutable]
sourceMap 695-4dd37417c69a0af66bac.js.map 342 bytes [emitted] [dev]
runtime modules 6.59 KiB 9 modules
@ -785,7 +785,7 @@ built modules 500 bytes [built]
./b/chunk.js + 1 modules (in Xdir/context-independence/b) 66 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms
asset main-6fe9478fbece50724f14.js 14.8 KiB [emitted] [immutable] (name: main)
asset main-7c4bd4d93894bc8263e9.js 14.8 KiB [emitted] [immutable] (name: main)
asset 695-828eb5c7418e1b8270bb.js 1.5 KiB [emitted] [immutable]
runtime modules 6.59 KiB 9 modules
orphan modules 19 bytes [orphan] 1 module
@ -799,7 +799,7 @@ built modules 500 bytes [built]
./a/chunk.js + 1 modules (in Xdir/context-independence/a) 66 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms
asset main-6fe9478fbece50724f14.js 14.8 KiB [emitted] [immutable] (name: main)
asset main-7c4bd4d93894bc8263e9.js 14.8 KiB [emitted] [immutable] (name: main)
asset 695-828eb5c7418e1b8270bb.js 1.5 KiB [emitted] [immutable]
runtime modules 6.59 KiB 9 modules
orphan modules 19 bytes [orphan] 1 module
@ -813,7 +813,7 @@ built modules 500 bytes [built]
./b/chunk.js + 1 modules (in Xdir/context-independence/b) 66 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms
asset main-dab0773b873a912c8caa.js 13.7 KiB [emitted] [immutable] (name: main)
asset main-7dd3306e33267a41ff55.js 13.7 KiB [emitted] [immutable] (name: main)
asset 695-ace208366ce0ce2556ef.js 1.01 KiB [emitted] [immutable]
runtime modules 6.59 KiB 9 modules
orphan modules 19 bytes [orphan] 1 module
@ -827,7 +827,7 @@ built modules 500 bytes [built]
./a/chunk.js + 1 modules (in Xdir/context-independence/a) 66 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms
asset main-dab0773b873a912c8caa.js 13.7 KiB [emitted] [immutable] (name: main)
asset main-7dd3306e33267a41ff55.js 13.7 KiB [emitted] [immutable] (name: main)
asset 695-ace208366ce0ce2556ef.js 1.01 KiB [emitted] [immutable]
runtime modules 6.59 KiB 9 modules
orphan modules 19 bytes [orphan] 1 module
@ -1179,7 +1179,7 @@ webpack x.x.x compiled with 2 warnings in X ms"
`;
exports[`StatsTestCases should print correct stats for immutable 1`] = `
"asset 3d65ee71fc9f53a687bd.js 13.3 KiB [emitted] [immutable] (name: main)
"asset 5d45ce8c58c0be47d4b1.js 13.3 KiB [emitted] [immutable] (name: main)
asset 22c24a3b26d46118dc06.js 809 bytes [emitted] [immutable]"
`;
@ -1269,10 +1269,10 @@ webpack x.x.x compiled successfully in X ms
assets by chunk 895 bytes (id hint: all)
asset c-all-b_js-d2d64fdaadbf1936503b.js 502 bytes [emitted] [immutable] (id hint: all)
asset c-all-c_js-0552c7cbb8c1a12b6b9c.js 393 bytes [emitted] [immutable] (id hint: all)
asset c-runtime~main-51dac241c7dc65379790.js 13.5 KiB [emitted] [immutable] (name: runtime~main)
asset c-runtime~main-39696e33891b24e372db.js 13.5 KiB [emitted] [immutable] (name: runtime~main)
asset c-main-463838c803f48fe97bb6.js 680 bytes [emitted] [immutable] (name: main)
asset c-vendors-node_modules_vendor_js-7320f018dbab7e34ead5.js 185 bytes [emitted] [immutable] (id hint: vendors)
Entrypoint main 14.6 KiB = c-runtime~main-51dac241c7dc65379790.js 13.5 KiB c-all-c_js-0552c7cbb8c1a12b6b9c.js 393 bytes c-main-463838c803f48fe97bb6.js 680 bytes
Entrypoint main 14.6 KiB = c-runtime~main-39696e33891b24e372db.js 13.5 KiB c-all-c_js-0552c7cbb8c1a12b6b9c.js 393 bytes c-main-463838c803f48fe97bb6.js 680 bytes
runtime modules 8.66 KiB 13 modules
cacheable modules 101 bytes
./c.js 61 bytes [built] [code generated]
@ -2157,7 +2157,7 @@ runtime modules 6 KiB
webpack/runtime/load script 1.36 KiB {179} [code generated]
[no exports]
[used exports unknown]
webpack/runtime/publicPath 867 bytes {179} [code generated]
webpack/runtime/publicPath 868 bytes {179} [code generated]
[no exports]
[used exports unknown]
cacheable modules 193 bytes
@ -2228,7 +2228,7 @@ LOG from webpack.FileSystemInfo
Directory info in cache: 0 timestamps 0 hashes 0 timestamp hash combinations
Managed items info in cache: 0 items
1970-04-20 12:42:42: webpack x.x.x compiled successfully in X ms (5966d7136f537890a286)"
1970-04-20 12:42:42: webpack x.x.x compiled successfully in X ms (44c013196446a1259957)"
`;
exports[`StatsTestCases should print correct stats for preset-errors-only 1`] = `""`;
@ -2427,7 +2427,7 @@ chunk {179} (runtime: main) main.js (main) 73 bytes (javascript) 6 KiB (runtime)
webpack/runtime/load script 1.36 KiB {179} [code generated]
[no exports]
[used exports unknown]
webpack/runtime/publicPath 867 bytes {179} [code generated]
webpack/runtime/publicPath 868 bytes {179} [code generated]
[no exports]
[used exports unknown]
cacheable modules 73 bytes
@ -2604,7 +2604,7 @@ LOG from webpack.FileSystemInfo
Directory info in cache: 0 timestamps 0 hashes 0 timestamp hash combinations
Managed items info in cache: 0 items
1970-04-20 12:42:42: webpack x.x.x compiled successfully in X ms (5966d7136f537890a286)"
1970-04-20 12:42:42: webpack x.x.x compiled successfully in X ms (44c013196446a1259957)"
`;
exports[`StatsTestCases should print correct stats for real-content-hash 1`] = `
@ -4675,3 +4675,13 @@ cacheable modules 2.31 KiB (javascript) 1.37 KiB (webassembly)
./node_modules/env.js 34 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms"
`;
exports[`StatsTestCases should print correct stats for worker-public-path 1`] = `
"asset main-27d65b836727f9226214.js 3.51 KiB [emitted] [immutable] (name: main)
asset 442-579eebb6602aecc20b13.js 219 bytes [emitted] [immutable]
runtime modules 1.75 KiB 5 modules
cacheable modules 250 bytes
./index.js 115 bytes [built] [code generated]
./worker.js 135 bytes [built] [code generated]
webpack x.x.x compiled successfully in X ms"
`;

View File

@ -0,0 +1,5 @@
import img from "./img.jpg";
it("should compile", () => {
expect(typeof img).toBe("string");
});

View File

@ -0,0 +1,24 @@
const findOutputFiles = require("../../../helpers/findOutputFiles");
const allAssets = new Set();
const allBundles = new Set();
module.exports = {
findBundle: function(i, options) {
const bundle = findOutputFiles(options, new RegExp(`^bundle${i}`))[0];
allBundles.add(/\.([^.]+)\./.exec(bundle)[1]);
const assets = findOutputFiles(options, /^img/);
for (const asset of assets) {
allAssets.add(asset);
}
return `./${bundle}`;
},
afterExecute: () => {
// Since there are exactly 2 unique values of output.hashSalt,
// there should be exactly 2 unique output hashes for each file.
expect(allBundles.size).toBe(2);
expect(allAssets.size).toBe(2);
}
};

View File

@ -0,0 +1,48 @@
/** @type {import("../../../../").Configuration[]} */
module.exports = [
{
output: {
filename: "bundle0.[contenthash].js",
assetModuleFilename: "[name].[contenthash][ext]",
hashSalt: "1"
},
module: {
rules: [
{
test: /\.jpg$/,
type: "asset/resource"
}
]
}
},
{
output: {
filename: "bundle1.[contenthash].js",
assetModuleFilename: "[name].[contenthash][ext]",
hashSalt: "1"
},
module: {
rules: [
{
test: /\.jpg$/,
type: "asset/resource"
}
]
}
},
{
output: {
filename: "bundle2.[contenthash].js",
assetModuleFilename: "[name].[contenthash][ext]",
hashSalt: "2"
},
module: {
rules: [
{
test: /\.jpg$/,
type: "asset/resource"
}
]
}
}
];

View File

@ -0,0 +1,3 @@
.bar {
color: #fff;
}

View File

@ -0,0 +1,7 @@
import { countBy } from "lodash-es";
import "./bar.css";
const result = countBy([6.1, 4.2, 6.3], Math.floor);
export default result["6"];

View File

@ -0,0 +1,3 @@
.foo {
color: #fff;
}

View File

@ -0,0 +1,7 @@
import { dropRight } from "lodash-es";
import "./foo.css";
const result = dropRight([10, 20, 30], 2);
export default result[0];

View File

@ -0,0 +1,15 @@
import foo from "./foo.js";
import bar from "./bar.js";
console.log(foo + bar);
it("should not contain non javascript chunk in the main bundle", () => {
const fs = require("fs");
const source = fs.readFileSync(__STATS__.outputPath + "/main.mjs", "utf-8");
expect(__STATS__.chunks.some(c => c.names.includes("style"))).toBe(true);
// Should not import "./style.mjs";`
expect(source).not.toMatch(
/import\s\*\sas+\s__webpack_chunk_[0-9]+__\sfrom\s"\.\/style\.mjs"/g
);
});

View File

@ -0,0 +1,5 @@
module.exports = {
findBundle: function (i, options) {
return ["main.mjs", "vendor.mjs", "runtime.mjs"];
}
};

View File

@ -0,0 +1,5 @@
const supportsRequireInModule = require("../../../helpers/supportsRequireInModule");
module.exports = () => {
return supportsRequireInModule();
};

View File

@ -0,0 +1,77 @@
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
mode: "production",
devtool: false,
experiments: {
outputModule: true
},
output: {
publicPath: "/",
filename: "[name].mjs",
chunkFilename: "[name].chunk.js",
assetModuleFilename: "[hash][ext][query]",
module: true,
libraryTarget: "module",
chunkFormat: "module",
chunkLoading: "import",
environment: {
dynamicImport: true,
module: true
}
},
module: {
rules: [
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: "style.css",
chunkFilename: "[id].css"
})
],
optimization: {
splitChunks: {
chunks: "all",
cacheGroups: {
style: {
name: "style",
type: "css/mini-extract",
chunks: "all",
enforce: true
},
defaultVendors: {
name: "vendor",
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: "initial",
reuseExistingChunk: true
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
},
runtimeChunk: {
name: "runtime"
},
// currently Webpack has bugs when setting concatenateModules to true while produce ES Module output.
// concatenateModules: false,
minimize: false
}
};

View File

@ -0,0 +1,14 @@
import { Worker } from "worker_threads";
it("should define public path", async () => {
const worker = new Worker(new URL("./worker.js", import.meta.url), {
type: "module"
});
worker.postMessage("ok");
var fs = require("fs"),
path = require("path");
var source = fs.readFileSync(path.join(__dirname, "main.js"), "utf-8");
expect(source).toMatch("workerPublicPath2");
await worker.terminate()
});

View File

@ -0,0 +1,5 @@
module.exports = {
findBundle: function () {
return ["./main.js"];
}
};

View File

@ -0,0 +1,5 @@
var supportsWorker = require("../../../helpers/supportsWorker");
module.exports = function (config) {
return supportsWorker();
};

View File

@ -0,0 +1,13 @@
/** @type {import("../../../../").Configuration} */
module.exports = {
mode: "none",
target: "node",
node: {
__dirname: false,
__filename: false
},
output: {
filename: "[name].js",
workerPublicPath: "/workerPublicPath2/"
}
};

View File

@ -0,0 +1,6 @@
function upper(str) {
return str.toUpperCase();
}
onmessage = async event => {
postMessage(`data: ${upper(event.data)}, thanks`);
};

1
test/fixtures/empty-svg-loader.js vendored Normal file
View File

@ -0,0 +1 @@
module.exports = () => "<svg></svg>";

1
test/fixtures/file.svg vendored Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 600"><title>icon-square-small</title><path fill="#FFF" d="M300 .1L565 150v299.9L300 599.8 35 449.9V150z"/><path fill="#8ED6FB" d="M517.7 439.5L308.8 557.8v-92L439 394.1l78.7 45.4zm14.3-12.9V179.4l-76.4 44.1v159l76.4 44.1zM81.5 439.5l208.9 118.2v-92l-130.2-71.6-78.7 45.4zm-14.3-12.9V179.4l76.4 44.1v159l-76.4 44.1zm8.9-263.2L290.4 42.2v89l-137.3 75.5-1.1.6-75.9-43.9zm446.9 0L308.8 42.2v89L446 206.8l1.1.6 75.9-44z"/><path fill="#1C78C0" d="M290.4 444.8L162 374.1V234.2l128.4 74.1v136.5zm18.4 0l128.4-70.6v-140l-128.4 74.1v136.5zM299.6 303zm-129-85l129-70.9L428.5 218l-128.9 74.4-129-74.4z"/></svg>

After

Width:  |  Height:  |  Size: 656 B

1
test/fixtures/uses-asset.js vendored Normal file
View File

@ -0,0 +1 @@
import SVG from './file.svg';

View File

@ -0,0 +1,4 @@
const worker = new Worker(new URL("./worker.js", import.meta.url), {
type: "module"
});
worker.postMessage("ok");

View File

@ -0,0 +1,8 @@
/** @type {import("../../../types").Configuration} */
module.exports = {
mode: "production",
entry: "./index.js",
output: {
filename: "[name]-[contenthash].js"
}
};

View File

@ -0,0 +1,6 @@
function upper(str) {
return str.toUpperCase();
}
onmessage = async event => {
postMessage(`data: ${upper(event.data)}, thanks`);
};

27
types.d.ts vendored
View File

@ -6600,6 +6600,12 @@ declare interface LoaderRunnerLoaderContext<OptionsType> {
* Example: "/abc/resource.js?query#frag"
*/
resource: string;
/**
* Target of compilation.
* Example: "web"
*/
target: string;
}
declare class LoaderTargetPlugin {
constructor(target: string);
@ -8684,6 +8690,11 @@ declare interface Output {
*/
workerChunkLoading?: string | false;
/**
* Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.
*/
workerPublicPath?: string;
/**
* The method of loading WebAssembly Modules (methods included by default are 'fetch' (web/WebWorker), 'async-node' (node.js), but others might be added by plugins).
*/
@ -8978,6 +8989,11 @@ declare interface OutputNormalized {
*/
workerChunkLoading?: string | false;
/**
* Worker public path. Much like the public path, this sets the location where the worker script file is intended to be found. If not set, webpack will use the publicPath. Don't set this option unless your worker scripts are located at a different path from your other script files.
*/
workerPublicPath?: string;
/**
* The method of loading WebAssembly Modules (methods included by default are 'fetch' (web/WebWorker), 'async-node' (node.js), but others might be added by plugins).
*/
@ -9362,6 +9378,15 @@ declare class RawSource extends Source {
constructor(source: string | Buffer, convertToString?: boolean);
isBuffer(): boolean;
}
declare interface RawSourceMap {
version: number;
sources: string[];
names: string[];
sourceRoot?: string;
sourcesContent?: string[];
mappings: string;
file: string;
}
declare class ReadFileCompileWasmPlugin {
constructor(options?: any);
options: any;
@ -11108,7 +11133,7 @@ declare abstract class SortableSet<T> extends Set<T> {
declare class Source {
constructor();
size(): number;
map(options?: MapOptions): Object;
map(options?: MapOptions): null | RawSourceMap;
sourceAndMap(options?: MapOptions): { source: string | Buffer; map: Object };
updateHash(hash: Hash): void;
source(): string | Buffer;

View File

@ -4154,10 +4154,10 @@ loader-utils@^1.1.0, loader-utils@^1.4.0:
emojis-list "^3.0.0"
json5 "^1.0.1"
loader-utils@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.0.tgz#e4cace5b816d425a166b5f097e10cd12b36064b0"
integrity sha512-rP4F0h2RaWSvPEkD7BLDFQnvSf+nK+wr3ESUjNTyAGobqrijmW92zc+SO6d4p4B1wh7+B/Jg1mkQe5NYUEHtHQ==
loader-utils@^2.0.0, loader-utils@^2.0.3:
version "2.0.3"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.3.tgz#d4b15b8504c63d1fc3f2ade52d41bc8459d6ede1"
integrity sha512-THWqIsn8QRnvLl0shHYVBN9syumU8pYWEHPTmkiVGd+7K5eFNVSY6AJhRvgGF70gg1Dz+l/k8WicvFCxdEs60A==
dependencies:
big.js "^5.2.2"
emojis-list "^3.0.0"