Skip to content

Conversation

@hadeeb
Copy link
Contributor

@hadeeb hadeeb commented Mar 17, 2025

This lets the Javascript minifiers remove these constants from the final bundle

Copy link
Member

@lpil lpil left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I tested this it didn't make any difference. Did you verify it working?

@hadeeb
Copy link
Contributor Author

hadeeb commented Mar 18, 2025

When I bundle the generated js code with esbuild, it pulls the globally defined constants.

esbuild build/dev/javascript/app/app.mjs --bundle --format=esm --target=node20

Generated output
import gleam/io
import gleam/string

pub fn main() {
  "Hello, Gleam!" |> string.lowercase |> io.println
}
// build/dev/javascript/gleam_stdlib/dict.mjs
var tempDataView = new DataView(new ArrayBuffer(8));
var SHIFT = 5;
var BUCKET_SIZE = Math.pow(2, SHIFT);
var MASK = BUCKET_SIZE - 1;
var MAX_INDEX_NODE = BUCKET_SIZE / 2;
var MIN_ARRAY_NODE = BUCKET_SIZE / 4;
var unequalDictSymbol = Symbol();

// build/dev/javascript/gleam_stdlib/gleam_stdlib.mjs
function lowercase(string) {
    return string.toLowerCase();
}
var unicode_whitespaces = [
    " ",
    // Space
    "	",
    // Horizontal tab
    "\n",
    // Line feed
    "\v",
    // Vertical tab
    "\f",
    // Form feed
    "\r",
    // Carriage return
    "\x85",
    // Next line
    "\u2028",
    // Line separator
    "\u2029",
    // Paragraph separator
].join("");
var trim_start_regex = new RegExp(`^[${unicode_whitespaces}]*`);
var trim_end_regex = new RegExp(`[${unicode_whitespaces}]*$`);
function console_log(term) {
    console.log(term);
}

// build/dev/javascript/app/app.mjs
function main() {
    let _pipe = "Hello, Gleam!";
    let _pipe$1 = lowercase(_pipe);
    return console_log(_pipe$1);
}
export { main };

Running terser or swc on this js bundle does not remove the constants, unless annotated as PURE.

SWC Playground

With Annotations

Rollup (and Vite, by extension) does not seem to import these unrelated constants.
Also, I am not sure how common the bundle with esbuild => run the minifier workflow is.

Copy link
Member

@lpil lpil left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! Thank you for that. Glad it's working now

@lpil lpil merged commit b649d35 into gleam-lang:main Mar 18, 2025
7 checks passed
@hadeeb hadeeb deleted the feature/treeshake-globals branch March 18, 2025 16:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants