itgalaxy / favicons

Favicons generator for Node.js
MIT License
1.19k stars 165 forks source link

feat: allow defining cwd paths #423

Open paul-vd opened 1 year ago

paul-vd commented 1 year ago

Why

When you programmatically try to run the favicons inside a node application, you might have the favicons script in subfolders, this will allow you to pass the process.cwd() to the options and prefix any source paths with the cwd folder. for example

import favicons from "favions"

favicons("/public/favicon.png", {
   path:"/favicons",
   manifestMaskable: "/public/images/favicon-mask.png",
   cwd: process.cwd()
})

Here is an example of running this from a different folder with node:

image

andy128k commented 1 year ago

why not to join before the invocation?

paul-vd commented 1 year ago

So in our use case, we have a framework which is consumed by other developers, they can configure the settings from their relative directory, and we then consume it under our installed package. We are currently doing that manually, but it could lead to issues, as we can not know which icons they have configured, here is an example of what we are currently doing

const withRootPath = (src: string) => {
  return path.join(process.cwd(), src);
};

// path might be a URL or Buffer, which we don't want to modify.
const isRelativePath = (input: any): input is string => {
  return typeof input === "string" && input.startsWith("/");
};

const extractFaviconsOptions = (
  { source, ...options } = {} as Required<PWAConfig>
) => {
  if (options?.manifestMaskable && isRelativePath(options.manifestMaskable)) {
    options.manifestMaskable = withRootPath(options.manifestMaskable);
  }

  if (options.shortcuts) {
    options.shortcuts = options.shortcuts.map((shortcut) => {
      if (isRelativePath(shortcut.icon)) {
        return {
          ...shortcut,
          icon: withRootPath(shortcut.icon),
        };
      }
      return shortcut;
    });
  }

  return options;
};

let source = userConfig.source
if(isRelativePath(source)){
  source = withRootPath(source);
}
const faviconOptions = extractFaviconsOptions(userConfig);
andy128k commented 1 year ago

Honestly, I don't see anything wrong with your current approach.