From 572452acf89be67f7e7985fdc9cf5e9e7fa705a0 Mon Sep 17 00:00:00 2001 From: fisker Cheung Date: Tue, 4 Oct 2022 18:09:24 +0800 Subject: [PATCH] Reduce size of `standalone.js` (#13543) --- scripts/build/build-javascript-module.js | 28 ++++++++++++++++++++++++ src/language-js/pragma.js | 12 +++++++--- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/scripts/build/build-javascript-module.js b/scripts/build/build-javascript-module.js index c81526a99..ad98469bf 100644 --- a/scripts/build/build-javascript-module.js +++ b/scripts/build/build-javascript-module.js @@ -61,6 +61,25 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { return text.slice(0, index); }, }, + /* + `jest-docblock` try to detect new line in code, and it will fallback to `os.EOL`, + We already replaced line end to `\n` before calling it + */ + { + module: require.resolve("jest-docblock"), + process: (text) => + text + .replace( + "const line = (0, _detectNewline().default)(docblock) || _os().EOL;", + 'const line = "\\n"' + ) + .replace( + "const line = (0, _detectNewline().default)(comments) || _os().EOL;", + 'const line = "\\n"' + ) + .replace(/\nfunction _os().*?\n}/s, "") + .replace(/\nfunction _detectNewline().*?\n}/s, ""), + }, ]; const define = { @@ -120,6 +139,15 @@ function getEsbuildOptions({ file, files, shouldCollectLicenses, cliOptions }) { find: 'import { createRequire } from "node:module";', replacement: "", }, + // Prevent `esbuildPluginNodeModulePolyfills` shim `assert`, which will include a big `buffer` shim + // TODO[@fisker]: Find a better way + { + module: "*", + find: ' from "node:assert";', + replacement: ` from ${JSON.stringify( + path.join(dirname, "./shims/assert.js") + )};`, + }, // Prevent `esbuildPluginNodeModulePolyfills` include shim for this module { module: "assert", diff --git a/src/language-js/pragma.js b/src/language-js/pragma.js index c64228cdc..8651163ad 100644 --- a/src/language-js/pragma.js +++ b/src/language-js/pragma.js @@ -23,7 +23,7 @@ function insertPragma(originalText) { const { shebang, text, pragmas, comments } = parseDocBlock(originalText); const strippedText = strip(text); - const docBlock = print({ + let docBlock = print({ pragmas: { format: "", ...pragmas, @@ -31,10 +31,16 @@ function insertPragma(originalText) { comments: comments.trimStart(), }); + // normalise newlines (mitigate use of os.EOL by jest-docblock) + // Only needed in development version on Windows, + // bundler will hack `jest-docblock` enforce it to use `\n` in production + if (process.env.NODE_ENV !== "production") { + docBlock = normalizeEndOfLine(docBlock); + } + return ( (shebang ? `${shebang}\n` : "") + - // normalise newlines (mitigate use of os.EOL by jest-docblock) - normalizeEndOfLine(docBlock) + + docBlock + (strippedText.startsWith("\n") ? "\n" : "\n\n") + strippedText );