refactor: use `module.parser.json.exportsDepth`

This commit is contained in:
hai-x 2024-12-14 01:14:02 +08:00
parent 38df65df32
commit 3de7b0d330
12 changed files with 94 additions and 33 deletions

View File

@ -5,6 +5,10 @@
*/ */
export interface JsonModulesPluginParserOptions { export interface JsonModulesPluginParserOptions {
/**
* The depth of json dependency flagged as `exportInfo`.
*/
exportsDepth?: number;
/** /**
* Function that executes for a module source string and should return json-compatible data. * Function that executes for a module source string and should return json-compatible data.
*/ */

View File

@ -78,8 +78,6 @@ class WebpackOptionsApply extends OptionsApply {
compiler.recordsOutputPath = options.recordsOutputPath || null; compiler.recordsOutputPath = options.recordsOutputPath || null;
compiler.name = options.name; compiler.name = options.name;
const development = options.mode === "development";
if (options.externals) { if (options.externals) {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697 // @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const ExternalsPlugin = require("./ExternalsPlugin"); const ExternalsPlugin = require("./ExternalsPlugin");
@ -292,9 +290,7 @@ class WebpackOptionsApply extends OptionsApply {
} }
new JavascriptModulesPlugin().apply(compiler); new JavascriptModulesPlugin().apply(compiler);
new JsonModulesPlugin({ new JsonModulesPlugin().apply(compiler);
depth: development ? 1 : Infinity
}).apply(compiler);
new AssetModulesPlugin().apply(compiler); new AssetModulesPlugin().apply(compiler);
if (!options.experiments.outputModule) { if (!options.experiments.outputModule) {

View File

@ -262,7 +262,8 @@ const applyWebpackOptionsDefaults = (options, compilerIndex) => {
futureDefaults, futureDefaults,
isNode: targetProperties && targetProperties.node === true, isNode: targetProperties && targetProperties.node === true,
uniqueName: options.output.uniqueName, uniqueName: options.output.uniqueName,
targetProperties targetProperties,
mode: options.mode
}); });
applyExternalsPresetsDefaults(options.externalsPresets, { applyExternalsPresetsDefaults(options.externalsPresets, {
@ -609,6 +610,7 @@ const applyCssGeneratorOptionsDefaults = (
* @param {string} options.uniqueName the unique name * @param {string} options.uniqueName the unique name
* @param {boolean} options.isNode is node target platform * @param {boolean} options.isNode is node target platform
* @param {TargetProperties | false} options.targetProperties target properties * @param {TargetProperties | false} options.targetProperties target properties
* @param {Mode} options.mode mode
* @returns {void} * @returns {void}
*/ */
const applyModuleDefaults = ( const applyModuleDefaults = (
@ -621,7 +623,8 @@ const applyModuleDefaults = (
futureDefaults, futureDefaults,
isNode, isNode,
uniqueName, uniqueName,
targetProperties targetProperties,
mode
} }
) => { ) => {
if (cache) { if (cache) {
@ -663,6 +666,12 @@ const applyModuleDefaults = (
} }
F(module.parser, "javascript", () => ({})); F(module.parser, "javascript", () => ({}));
F(module.parser, JSON_MODULE_TYPE, () => ({}));
D(
module.parser[JSON_MODULE_TYPE],
"exportsDepth",
mode === "development" ? 1 : Infinity
);
applyJavascriptParserOptionsDefaults( applyJavascriptParserOptionsDefaults(
/** @type {NonNullable<ParserOptionsByModuleTypeKnown["javascript"]>} */ /** @type {NonNullable<ParserOptionsByModuleTypeKnown["javascript"]>} */

View File

@ -19,15 +19,15 @@ const NullDependency = require("./NullDependency");
/** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */ /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("../util/Hash")} Hash */ /** @typedef {import("../util/Hash")} Hash */
/** @typedef {{depth:number}} JsonDependencyOptions */ /** @typedef {{exportsDepth:number}} JsonDependencyOptions */
/** /**
* @param {number} depth depth * @param {number} exportsDepth exportsDepth
* @returns {((data: RawJsonData, curDepth?: number) => ExportSpec[] | undefined)} value * @returns {((data: RawJsonData, curDepth?: number) => ExportSpec[] | undefined)} value
*/ */
const getExportsWithDepth = depth => const getExportsWithDepth = exportsDepth =>
function getExportsFromData(data, curDepth = 1) { function getExportsFromData(data, curDepth = 1) {
if (curDepth > depth) return undefined; if (curDepth > exportsDepth) return undefined;
if (data && typeof data === "object") { if (data && typeof data === "object") {
if (Array.isArray(data)) { if (Array.isArray(data)) {
return data.length < 100 return data.length < 100
@ -54,12 +54,12 @@ const getExportsWithDepth = depth =>
class JsonExportsDependency extends NullDependency { class JsonExportsDependency extends NullDependency {
/** /**
* @param {JsonData} data json data * @param {JsonData} data json data
* @param {JsonDependencyOptions} dependencyOptions dependency options * @param {JsonDependencyOptions} options options
*/ */
constructor(data, dependencyOptions) { constructor(data, options) {
super(); super();
this.data = data; this.data = data;
this.options = dependencyOptions; this.options = options;
} }
get type() { get type() {
@ -73,7 +73,7 @@ class JsonExportsDependency extends NullDependency {
*/ */
getExports(moduleGraph) { getExports(moduleGraph) {
return { return {
exports: getExportsWithDepth(this.options.depth)( exports: getExportsWithDepth(this.options.exportsDepth)(
this.data && /** @type {RawJsonData} */ (this.data.get()) this.data && /** @type {RawJsonData} */ (this.data.get())
), ),
dependencies: undefined dependencies: undefined

View File

@ -11,7 +11,6 @@ const JsonGenerator = require("./JsonGenerator");
const JsonParser = require("./JsonParser"); const JsonParser = require("./JsonParser");
/** @typedef {import("../Compiler")} Compiler */ /** @typedef {import("../Compiler")} Compiler */
/** @typedef {import("../dependencies/JsonExportsDependency").JsonDependencyOptions} JsonDependencyOptions */
/** @typedef {Record<string, any>} RawJsonData */ /** @typedef {Record<string, any>} RawJsonData */
const validate = createSchemaValidation( const validate = createSchemaValidation(
@ -30,13 +29,6 @@ const PLUGIN_NAME = "JsonModulesPlugin";
* It adds the json module type to the compiler and registers the json parser and generator. * It adds the json module type to the compiler and registers the json parser and generator.
*/ */
class JsonModulesPlugin { class JsonModulesPlugin {
/**
* @param {JsonDependencyOptions} dependencyOptions dependency options
*/
constructor(dependencyOptions) {
this.dependencyOptions = dependencyOptions;
}
/** /**
* Apply the plugin * Apply the plugin
* @param {Compiler} compiler the compiler instance * @param {Compiler} compiler the compiler instance
@ -50,8 +42,7 @@ class JsonModulesPlugin {
.for(JSON_MODULE_TYPE) .for(JSON_MODULE_TYPE)
.tap(PLUGIN_NAME, parserOptions => { .tap(PLUGIN_NAME, parserOptions => {
validate(parserOptions); validate(parserOptions);
return new JsonParser(parserOptions);
return new JsonParser(parserOptions, this.dependencyOptions);
}); });
normalModuleFactory.hooks.createGenerator normalModuleFactory.hooks.createGenerator
.for(JSON_MODULE_TYPE) .for(JSON_MODULE_TYPE)

View File

@ -15,20 +15,17 @@ const JsonData = require("./JsonData");
/** @typedef {import("../Module").BuildMeta} BuildMeta */ /** @typedef {import("../Module").BuildMeta} BuildMeta */
/** @typedef {import("../Parser").ParserState} ParserState */ /** @typedef {import("../Parser").ParserState} ParserState */
/** @typedef {import("../Parser").PreparsedAst} PreparsedAst */ /** @typedef {import("../Parser").PreparsedAst} PreparsedAst */
/** @typedef {import("../dependencies/JsonExportsDependency").JsonDependencyOptions} JsonDependencyOptions */
/** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */ /** @typedef {import("./JsonModulesPlugin").RawJsonData} RawJsonData */
const getParseJson = memoize(() => require("json-parse-even-better-errors")); const getParseJson = memoize(() => require("json-parse-even-better-errors"));
class JsonParser extends Parser { class JsonParser extends Parser {
/** /**
* @param {JsonModulesPluginParserOptions} parserOptions parser options * @param {JsonModulesPluginParserOptions} options parser options
* @param {JsonDependencyOptions} dependencyOptions dependency options
*/ */
constructor(parserOptions, dependencyOptions) { constructor(options) {
super(); super();
this.options = parserOptions || {}; this.options = options || {};
this.dependencyOptions = dependencyOptions;
} }
/** /**
@ -67,7 +64,9 @@ class JsonParser extends Parser {
buildMeta.defaultObject = buildMeta.defaultObject =
typeof data === "object" ? "redirect-warn" : false; typeof data === "object" ? "redirect-warn" : false;
state.module.addDependency( state.module.addDependency(
new JsonExportsDependency(jsonData, this.dependencyOptions) new JsonExportsDependency(jsonData, {
exportsDepth: this.options.exportsDepth
})
); );
return state; return state;
} }

View File

@ -3,4 +3,4 @@
* DO NOT MODIFY BY HAND. * DO NOT MODIFY BY HAND.
* Run `yarn special-lint-fix` to update * Run `yarn special-lint-fix` to update
*/ */
"use strict";function r(t,{instancePath:e="",parentData:a,parentDataProperty:o,rootData:n=t}={}){if(!t||"object"!=typeof t||Array.isArray(t))return r.errors=[{params:{type:"object"}}],!1;{const e=0;for(const e in t)if("parse"!==e)return r.errors=[{params:{additionalProperty:e}}],!1;if(0===e&&void 0!==t.parse&&!(t.parse instanceof Function))return r.errors=[{params:{}}],!1}return r.errors=null,!0}module.exports=r,module.exports.default=r; "use strict";function r(e,{instancePath:t="",parentData:o,parentDataProperty:a,rootData:s=e}={}){if(!e||"object"!=typeof e||Array.isArray(e))return r.errors=[{params:{type:"object"}}],!1;{const t=0;for(const t in e)if("exportsDepth"!==t&&"parse"!==t)return r.errors=[{params:{additionalProperty:t}}],!1;if(0===t){if(void 0!==e.exportsDepth){const t=0;if("number"!=typeof e.exportsDepth)return r.errors=[{params:{type:"number"}}],!1;var n=0===t}else n=!0;if(n)if(void 0!==e.parse){const t=0;if(!(e.parse instanceof Function))return r.errors=[{params:{}}],!1;n=0===t}else n=!0}}return r.errors=null,!0}module.exports=r,module.exports.default=r;

View File

@ -3,6 +3,10 @@
"type": "object", "type": "object",
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
"exportsDepth": {
"description": "The depth of json dependency flagged as `exportInfo`.",
"type": "number"
},
"parse": { "parse": {
"description": "Function that executes for a module source string and should return json-compatible data.", "description": "Function that executes for a module source string and should return json-compatible data.",
"instanceof": "Function", "instanceof": "Function",

View File

@ -254,6 +254,9 @@ describe("snapshots", () => {
"wrappedContextRecursive": true, "wrappedContextRecursive": true,
"wrappedContextRegExp": /\\.\\*/, "wrappedContextRegExp": /\\.\\*/,
}, },
"json": Object {
"exportsDepth": Infinity,
},
}, },
"rules": Array [], "rules": Array [],
"unsafeCache": false, "unsafeCache": false,
@ -845,6 +848,9 @@ describe("snapshots", () => {
- "mode": "none", - "mode": "none",
+ "mode": "development", + "mode": "development",
@@ ... @@ @@ ... @@
- "exportsDepth": Infinity,
+ "exportsDepth": 1,
@@ ... @@
- "unsafeCache": false, - "unsafeCache": false,
+ "unsafeCache": [Function anonymous], + "unsafeCache": [Function anonymous],
@@ ... @@ @@ ... @@
@ -1905,6 +1911,9 @@ describe("snapshots", () => {
- "mode": "none", - "mode": "none",
+ "mode": "development", + "mode": "development",
@@ ... @@ @@ ... @@
- "exportsDepth": Infinity,
+ "exportsDepth": 1,
@@ ... @@
- "unsafeCache": false, - "unsafeCache": false,
+ "unsafeCache": [Function anonymous], + "unsafeCache": [Function anonymous],
@@ ... @@ @@ ... @@

View File

@ -0,0 +1,27 @@
{
"depth_1": {
"depth_2": {
"depth_3": {
"depth_4": {
"depth_5": {
"depth_6": "depth_6"
}
}
}
}
},
"_depth_1": {
"_depth_2": {
"_depth_3": {
"_depth_4": {
"_depth_5": {
"_depth_6": "_depth_6"
}
}
}
}
},
"__depth_1": [
{ "__depth_3": [{ "__depth_5": [{ "__depth_7": ["__depth_8"] }] }] }
]
}

View File

@ -0,0 +1,11 @@
export * from './data.json';
it("should compile and run", () => {
expect(__webpack_exports_info__.depth_1.provideInfo).toBe(true)
expect(__webpack_exports_info__._depth_1.provideInfo).toBe(true)
expect(__webpack_exports_info__.__depth_1.provideInfo).toBe(true)
expect(__webpack_exports_info__.depth_1.depth_2.provideInfo).toBe(true)
expect(__webpack_exports_info__._depth_1._depth_2._depth_3._depth_4.provideInfo).toBe(true)
expect(__webpack_exports_info__.__depth_1[0].__depth_3[0].__depth_5.provideInfo).toBe(true)
});

View File

@ -0,0 +1,11 @@
/** @type {import("../../../../").Configuration} */
module.exports = {
mode: "development",
module: {
parser: {
json: {
exportsDepth: Infinity
}
}
}
};