#Invalid tree shaking?

5 messages · Page 1 of 1 (latest)

neon light
#

I'm not sure why some of my code is not in build..

Here is my file:

let fs: any = null;
let path: any = null;
let fileURLToPath: any = null;
let __dirname = '';
let fetch: any = null;

const NODE_ENV = process.env.NODE_ENV;
const BASE_URL = import.meta.env.BASE_URL;

if (import.meta.env.SSR) {
  fs = (await import('fs')).default;
  path = (await import('path')).default;
  fileURLToPath = (await import('url')).fileURLToPath;
  __dirname = path.dirname(fileURLToPath(import.meta.url));
  fetch = (await import('sync-fetch')).default;
}

const isValidUrl = (urlString: string) => {
  try {
    return Boolean(new URL(urlString));
  } catch (e) {
    return false;
  }
};

export default function getImage(url: string, name: string) {
  const cacheBase = 'cache/images';

  if (!isValidUrl(url) || url === '' || url.length <= 1) {
    console.warn('invalid url passed to getImage()', url, name);
    return url; // return the url if it is not valid
  }

  if (import.meta.env.SSR) {
    const cache = `${path.resolve(__dirname, './' + cacheBase)}`;

    if (!fs.existsSync(cache)) {
      // console.log('image cache does not exist');
      fs.mkdirSync(cache, { recursive: true });
    }

    const imagePath = `${cache}/${name}`;

    // Check if "cached" file exists
    if (!fs.existsSync(`${cache}/${name}`)) {
      // @ts-ignore
      const res = fetch(url).buffer();

      // write res buffer to file
      fs.writeFileSync(imagePath, res);
    }

    return `${BASE_URL ?? ''}${cacheBase}/${name}`;
  } else {
    const fetchUrl =
      NODE_ENV !== 'development'
        ? `${BASE_URL ?? ''}${cacheBase}/${name}`
        : url;

    return fetchUrl;
  }
}

Here is the built file:

const n = n=>{
    try {
        return Boolean(new URL(n))
    } catch {
        return !1
    }
}
;
function r(r, e) {
    return (!n(r) || "" === r || r.length <= 1) && console.warn("invalid url passed to getImage()", r, e),
    r
}
export {r as g};
#

As you can see it decided that my else statement wasn't important enough to build out.

#

Any ideas?

deep tendon
#

linking the discussion from <#framework message>

#

the else statement was actually built out, but because NODE_ENV was production, fetchUrl is simply url, so further tree-shaking everything, the function returns the url only