Skip to content

Preconstruct strips out browser env check for .browser.{cjs, esm}.js build files #494

Open

Description

@ajimae

Issue:

In snippet.ts I have the following snippet which checks for browser environment.

// snippet.ts
const isBrowser = () =>
  typeof window !== 'undefined' &&
  window.document &&
  window.document.nodeType === 9

In the build files snippet.browser.cjs.js and snippet.browser.esm.js the above snippet is transpiled into:

// snippet.browser.cjs.js or snippet.browser.esm.js
const isBrowser = () =>
  window.document &&
  window.document.nodeType === 9

stripping out the typeof window !== 'undefined' check.

However, in the build files snippet.cjs.js and snippet.esm.js the above snippet is transpiled into:

// snippet.cjs.js or snippet.esm.js
const isBrowser = () =>
  typeof window !== 'undefined' &&
  window.document &&
  window.document.nodeType === 9

as expected.

Expected behaviour:

This very check typeof window !== 'undefined' should not be stripped out of the *.broswer.cjs.js and *.browser.esm.js build files.

Question:

  • Why is this the behaviour?
  • Is there a way to prevent this?

Activity

  1. emmatown commented on Sep 27, 2022

    @emmatown
    Member

    Replacing typeof window with "object" and dead code elimination from that is the entire behavior of the browser builds, if you'd like to avoid it, you can avoid generating browser builds and use the general builds in browsers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions