Skip to content

Commit

Permalink
Merge branch 'webpack:main' into webpack#17861
Browse files Browse the repository at this point in the history
  • Loading branch information
cherish2003 committed Dec 30, 2023
2 parents 82d849f + 42fd096 commit fd8c542
Show file tree
Hide file tree
Showing 26 changed files with 264 additions and 17 deletions.
10 changes: 5 additions & 5 deletions .github/workflows/test.yml
Expand Up @@ -19,7 +19,7 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
Expand All @@ -35,7 +35,7 @@ jobs:
basic:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
Expand All @@ -52,7 +52,7 @@ jobs:
validate-legacy-node:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
Expand All @@ -64,7 +64,7 @@ jobs:
unit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
Expand Down Expand Up @@ -115,7 +115,7 @@ jobs:
use_main_branches: 1
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
Expand Down
26 changes: 25 additions & 1 deletion examples/build-common.js
Expand Up @@ -51,7 +51,30 @@ const doCompileAndReplace = (args, prefix, callback) => {
throw new Error("Please install webpack-cli at root.");
}

cp.exec(`node ${path.resolve(__dirname, "../bin/webpack.js")} ${args} ${displayReasons} ${commonArgs}`, (error, stdout, stderr) => {
const connectIO = (subprocess) => {
const { stdin, stdout, stderr } = process;
const { stdin: _stdin, stdout: _stdout, stderr: _stderr } = subprocess;
const inputPair = [[stdin, _stdin]];
const outputPair = [[stdout, _stdout], [stderr, _stderr]];
inputPair.forEach(pair => {
pair[0].pipe(pair[1])
})
outputPair.forEach(pair => {
pair[1].pipe(pair[0])
})
disconnectIO = () => {
inputPair.forEach(pair => {
pair[0].unpipe(pair[1])
})
outputPair.forEach(pair => {
pair[1].unpipe(pair[0])
})
}
}
let disconnectIO = null;

const subprocess = cp.exec(`node ${path.resolve(__dirname, "../bin/webpack.js")} ${args} ${displayReasons} ${commonArgs}`, (error, stdout, stderr) => {
disconnectIO && disconnectIO();
if (stderr)
console.log(stderr);
if (error !== null)
Expand All @@ -64,6 +87,7 @@ const doCompileAndReplace = (args, prefix, callback) => {
}
callback();
});
connectIO(subprocess);
};

async.series([
Expand Down
47 changes: 47 additions & 0 deletions examples/stats-none/README.md
@@ -0,0 +1,47 @@
This configuration will enable the none output for the stats report.

You see that everything is working nicely together.

# example.js

```javascript
console.log("Hello World!");
```

# webpack.config.js

```javascript
const path = require("path");

module.exports = {
output: {
path: path.join(__dirname, "dist"),
filename: "output.js"
},
stats: "none"
};
```

# dist/output.js

```javascript
/******/ (() => { // webpackBootstrap
var __webpack_exports__ = {};
/*!********************!*\
!*** ./example.js ***!
\********************/
/*! unknown exports (runtime-defined) */
/*! runtime requirements: */
console.log("Hello World!");

/******/ })()
;
```

# Info

## Production mode

```
```
4 changes: 4 additions & 0 deletions examples/stats-none/build.js
@@ -0,0 +1,4 @@
global.NO_REASONS = true;
global.NO_STATS_OPTIONS = true;
global.STATS_COLORS = true;
require("../build-common");
1 change: 1 addition & 0 deletions examples/stats-none/example.js
@@ -0,0 +1 @@
console.log("Hello World!");
29 changes: 29 additions & 0 deletions examples/stats-none/template.md
@@ -0,0 +1,29 @@
This configuration will enable the none output for the stats report.

You see that everything is working nicely together.

# example.js

```javascript
_{{example.js}}_
```

# webpack.config.js

```javascript
_{{webpack.config.js}}_
```

# dist/output.js

```javascript
_{{dist/output.js}}_
```

# Info

## Production mode

```
_{{production:stdout}}_
```
9 changes: 9 additions & 0 deletions examples/stats-none/webpack.config.js
@@ -0,0 +1,9 @@
const path = require("path");

module.exports = {
output: {
path: path.join(__dirname, "dist"),
filename: "output.js"
},
stats: "none"
};
3 changes: 2 additions & 1 deletion lib/Compilation.js
Expand Up @@ -4927,7 +4927,8 @@ This prevents using hashes of each other and should be avoided.`);
hashFunction,
runtimeTemplate,
hashDigest,
hashDigestLength
hashDigestLength,
errors
);
}

Expand Down
5 changes: 4 additions & 1 deletion lib/LibManifestPlugin.js
Expand Up @@ -46,7 +46,10 @@ class LibManifestPlugin {
*/
apply(compiler) {
compiler.hooks.emit.tapAsync(
"LibManifestPlugin",
{
name: "LibManifestPlugin",
stage: 110
},
(compilation, callback) => {
const moduleGraph = compilation.moduleGraph;
asyncLib.forEach(
Expand Down
32 changes: 26 additions & 6 deletions lib/dependencies/ImportDependency.js
Expand Up @@ -48,12 +48,32 @@ class ImportDependency extends ModuleDependency {
* @returns {(string[] | ReferencedExport)[]} referenced exports
*/
getReferencedExports(moduleGraph, runtime) {
return this.referencedExports
? this.referencedExports.map(e => ({
name: e,
canMangle: false
}))
: Dependency.EXPORTS_OBJECT_REFERENCED;
if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED;
const refs = [];
for (const referencedExport of this.referencedExports) {
if (referencedExport[0] === "default") {
const selfModule = moduleGraph.getParentModule(this);
const importedModule =
/** @type {Module} */
(moduleGraph.getModule(this));
const exportsType = importedModule.getExportsType(
moduleGraph,
/** @type {BuildMeta} */
(selfModule.buildMeta).strictHarmonyModule
);
if (
exportsType === "default-only" ||
exportsType === "default-with-named"
) {
return Dependency.EXPORTS_OBJECT_REFERENCED;
}
}
refs.push({
name: referencedExport,
canMangle: false
});
}
return refs;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion lib/json/JsonGenerator.js
Expand Up @@ -183,7 +183,7 @@ class JsonGenerator extends Generator {
const jsonStr = /** @type {string} */ (stringifySafe(finalJson));
const jsonExpr =
jsonStr.length > 20 && typeof finalJson === "object"
? `JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')`
? `/*#__PURE__*/JSON.parse('${jsonStr.replace(/[\\']/g, "\\$&")}')`
: jsonStr;
/** @type {string} */
let content;
Expand Down
2 changes: 1 addition & 1 deletion lib/webworker/ImportScriptsChunkLoadingRuntimeModule.js
Expand Up @@ -196,7 +196,7 @@ class ImportScriptsChunkLoadingRuntimeModule extends RuntimeModule {
Template.getFunctionContent(
require("../hmr/JavascriptHotModuleReplacement.runtime.js")
)
.replace(/\$key\$/g, "importScrips")
.replace(/\$key\$/g, "importScripts")
.replace(/\$installedChunks\$/g, "installedChunks")
.replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk")
.replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache)
Expand Down
2 changes: 1 addition & 1 deletion test/__snapshots__/StatsTestCases.basictest.js.snap
Expand Up @@ -1274,7 +1274,7 @@ chunk (runtime: main) trees.js (trees) 215 bytes [rendered]
`;

exports[`StatsTestCases should print correct stats for ignore-warnings 1`] = `
"asset main.js 989 bytes [emitted] (name: main)
"asset main.js 1000 bytes [emitted] (name: main)
orphan modules 617 bytes [orphan] 9 modules
./index.js + 9 modules 790 bytes [built] [code generated]
Expand Down
2 changes: 2 additions & 0 deletions test/cases/chunks/destructuring-assignment/dir2/a.js
@@ -0,0 +1,2 @@
exports.a = 1;
exports.b = 2;
@@ -0,0 +1 @@
["a"]
@@ -0,0 +1 @@
{"a": 1}
@@ -0,0 +1 @@
"a"
11 changes: 11 additions & 0 deletions test/cases/chunks/destructuring-assignment/index.js
Expand Up @@ -10,3 +10,14 @@ it("should get warning on using 'webpackExports' with destructuring assignment",
expect(def).toBe(3);
done();
});

it("should not tree-shake default export for exportsType=default module", async () => {
const { default: object } = await import("./dir2/json/object.json");
const { default: array } = await import("./dir2/json/array.json");
const { default: primitive } = await import("./dir2/json/primitive.json");
expect(object).toEqual({ a: 1 });
expect(array).toEqual(["a"]);
expect(primitive).toBe("a");
const { default: a } = await import("./dir2/a");
expect(a).toEqual({ a: 1, b: 2 });
});
2 changes: 2 additions & 0 deletions test/cases/chunks/inline-options/dir15/a.js
@@ -0,0 +1,2 @@
exports.a = 1;
exports.b = 2;
1 change: 1 addition & 0 deletions test/cases/chunks/inline-options/dir15/json/array.json
@@ -0,0 +1 @@
["a"]
1 change: 1 addition & 0 deletions test/cases/chunks/inline-options/dir15/json/object.json
@@ -0,0 +1 @@
{"a": 1}
1 change: 1 addition & 0 deletions test/cases/chunks/inline-options/dir15/json/primitive.json
@@ -0,0 +1 @@
"a"
16 changes: 16 additions & 0 deletions test/cases/chunks/inline-options/index.js
Expand Up @@ -180,13 +180,29 @@ if (process.env.NODE_ENV === "production") {
}
);
});

it("should be able to load with webpackFetchPriorty high, low and auto", function () {
return Promise.all([
import(/* webpackFetchPriority: "high"*/ "./dir14/a"),
import(/* webpackFetchPriority: "low"*/ "./dir14/b"),
import(/* webpackFetchPriority: "auto"*/ "./dir14/c"),
])
})

it("should not tree-shake default export for exportsType=default module", async function () {
const jsonObject = await import(/* webpackExports: ["default"] */ "./dir15/json/object.json");
const jsonArray = await import(/* webpackExports: ["default"] */ "./dir15/json/array.json");
const jsonPrimitive = await import(/* webpackExports: ["default"] */ "./dir15/json/primitive.json");
expect(jsonObject.default).toEqual({ a: 1 });
expect(jsonObject.a).toEqual(1);
expect(jsonArray.default).toEqual(["a"]);
expect(jsonArray[0]).toBe("a");
expect(jsonPrimitive.default).toBe("a");
const a = await import(/* webpackExports: ["default"] */"./dir15/a");
expect(a.default).toEqual({ a: 1, b: 2 });
expect(a.a).toBe(1);
expect(a.b).toBe(2);
})
}

function testChunkLoading(load, expectedSyncInitial, expectedSyncRequested) {
Expand Down
1 change: 1 addition & 0 deletions test/configCases/clean/lib-manifest-plugin/index.js
@@ -0,0 +1 @@
it("should compile and run the test", function() {});
38 changes: 38 additions & 0 deletions test/configCases/clean/lib-manifest-plugin/readdir.js
@@ -0,0 +1,38 @@
const fs = require('fs');
const path = require('path');

function handlePath(path) {
return path.replace(/\\/g, "/");
}

module.exports = function readDir(from) {
const collectedFiles = [];
const collectedDirectories = [];
const stack = [from];
let cursor;

while ((cursor = stack.pop())) {
const stat = fs.statSync(cursor);

if (stat.isDirectory()) {
const items = fs.readdirSync(cursor);

if (from !== cursor) {
const relative = path.relative(from, cursor);
collectedDirectories.push(handlePath(relative));
}

for (let i = 0; i < items.length; i++) {
stack.push(path.join(cursor, items[i]));
}
} else {
const relative = path.relative(from, cursor);
collectedFiles.push(handlePath(relative));
}
}

return {
files: collectedFiles,
directories: collectedDirectories
};
}

0 comments on commit fd8c542

Please sign in to comment.