From a8e9e3e2d3e81bb7463162b8cfadb784dac7ee0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicol=C3=B2=20Ribaudo?= Date: Thu, 9 May 2024 15:11:59 +0200 Subject: [PATCH] Update the Babel plugin to remove empty class constructors This only happens when it's safe to do so. The exceptions are: - when the class extends another subclass: removing the constructor would remove the error about the missing super() call - when there are default parameters, that could have side effects - when there are destructured prameters, that could have side effects --- .../babel-plugin-pdfjs-preprocessor.mjs | 18 ++++++++++++++++ .../fixtures_babel/constructors-expected.js | 17 +++++++++++++++ .../builder/fixtures_babel/constructors.js | 21 +++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 external/builder/fixtures_babel/constructors-expected.js create mode 100644 external/builder/fixtures_babel/constructors.js diff --git a/external/builder/babel-plugin-pdfjs-preprocessor.mjs b/external/builder/babel-plugin-pdfjs-preprocessor.mjs index 945d22c473241c..4a81312dbad458 100644 --- a/external/builder/babel-plugin-pdfjs-preprocessor.mjs +++ b/external/builder/babel-plugin-pdfjs-preprocessor.mjs @@ -234,6 +234,24 @@ function babelPluginPDFJSPreprocessor(babel, ctx) { } }, }, + ClassMethod(path) { + const { + node, + parentPath: { parent: classNode }, + } = path; + if ( + // Remove empty constructors. We only do this for + // base classes, as the default constructor of derived + // classes is not empty (and an empty constructor + // must throw at runtime when constructed) + node.kind === "constructor" && + node.body.body.length === 0 && + node.params.every(p => p.type === "Identifier") && + !classNode.superClass + ) { + path.remove(); + } + }, }, }; } diff --git a/external/builder/fixtures_babel/constructors-expected.js b/external/builder/fixtures_babel/constructors-expected.js new file mode 100644 index 00000000000000..785956ef67dbc9 --- /dev/null +++ b/external/builder/fixtures_babel/constructors-expected.js @@ -0,0 +1,17 @@ +class A { + constructor() { + console.log("Hi!"); + } +} +class B { + constructor(x = console.log("Hi!")) {} +} +class C { + constructor({ + x + }) {} +} +class D {} +class E extends A { + constructor() {} +} diff --git a/external/builder/fixtures_babel/constructors.js b/external/builder/fixtures_babel/constructors.js new file mode 100644 index 00000000000000..fa7141306476fd --- /dev/null +++ b/external/builder/fixtures_babel/constructors.js @@ -0,0 +1,21 @@ +class A { + constructor() { + console.log("Hi!"); + } +} + +class B { + constructor(x = console.log("Hi!")) {} +} + +class C { + constructor({ x }) {} +} + +class D { + constructor(x, y, z) {} +} + +class E extends A { + constructor() {} +}