1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Check for browser optional chaining support in Angular project

Discussão em 'Angular' iniciado por Lincoln Alves, Setembro 29, 2024.

  1. In an Angular app, I want to check client's browser native support to optional chaining (es2020) in order to load a library which have a modern ES version and a legacy one.

    The problem is: Angular compiler (I believe it's actually tsc genera behaviour) transpiles everything to targeted ES version (es6 in my case), breaking the code I would use to check for optional chaining support (breaking in the sense that it won't work to check optional chaining support during runtime):


    export function isOpChainingSupported(): boolean {
    const opChainingChecker = {
    support: true
    };
    try {
    // CODE BEFORE TRANSPILING:
    // return opChainingChecker?.support;
    //
    // TURNS INTO
    return
    opChainingChecker === null || opChainingChecker === void 0 ?
    void 0 :
    opChainingChecker.support;
    } catch {
    return false;
    }
    }

    I tried using moving this code to a function in a plain JS file, using the 'allowJs' TS config in order to import it without errors...no go: tsc ends up transpiling it too.

    Now I can see three options I don't really like:

    • Using eval('constObj?.prop'), which is not a good option according to most sources I've checked for security reasons;
    • Using my plain JS file as an asset, loading it dynamically;
    • Creating a ES utility library for this function (my choice right now, even though I see it as an overkill for my problem).

    What I wanted to ask is: is there something I'm not seeing? A simpler solution that I've missed?

    Sorry in advance if this is a bad question, but I feel like when we "tinker" too much with a problem, it's always better to ask people with a fresh view of the picture!

    Cheers!

    Continue reading...

Compartilhe esta Página