svgo: CLI option to disable plugins is no longer available

I used an old version of SVGO like e.g. comand

svgo -i input.svg -o output.svg --pretty --indent=1 -p 3 --enable=removeHiddenElems --disable=removeUnknownsAndDefaults

and I got error: unknown option '--enable=removeHiddenElems'

However it seems svgo is not backwards compatible.

I have read #1329 and #1337/files, and do not understand what to do.

I have tried to copy svgo.config.js from https://github.com/svg/svgo/issues/1329#issuecomment-781585374 into the current folder and got

Error: Cannot find module 'svgo'
Require stack:
- /home/jkalliau/Documents/GitHub/cleanupSVG/svgo.config.js
- /home/jkalliau/prgm/node-v15.4.0-linux-x64/lib/node_modules/svgo/lib/svgo-node.js
- /home/jkalliau/prgm/node-v15.4.0-linux-x64/lib/node_modules/svgo/lib/svgo/coa.js
- /home/jkalliau/prgm/node-v15.4.0-linux-x64/lib/node_modules/svgo/bin/svgo
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (/home/jkalliau/Documents/GitHub/cleanupSVG/svgo.config.js:3:34)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Comments: 15 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Came here for a similar reason: after my weekly update I had a lot of CI builds failing with error: unknown option '--disable=removeViewBox'.

The releases notes for 2.0.0 suggests that --disable/--enable might be reimplemented in a later version, so I’ll simply stick to svgo@1.3.2 in the meantime. The amount of configuration needed in 2.0.0 to simply disable one plugin seems a bit overkill in my case.

I would like the reimplementation of --enable=PLUGIN-feature. (maybe I switch back to the buggy 1.3.2-version)

I had closed the issue, since I was able to solve the error, not meaning I’m anyhow happy with the solution/workaround.

Imho this bug-report/question is solved, but we should file a new feature-request. Since I do not know any duplicate/feature-request I reopen this issue for now, however it is up to the svgo-mebers how to proceed.

Only possible with config for now

Let me preface this by saying I do admire and appreciate the team’s decision to, as a wise famous man once said: “Move Fast and Break Things”

However… I, too, was just bitten by the removal of the --enable=PLUGIN CLI argument. 😦

I would vote that this issue be reopened, lest people inadvertently start creating duplicates. (I almost did!)

Hi. You need to install svgo locally like this npm i svgo

(Not sure if there’s more to say, but if this tangent continues, perhaps we can pursue email instead though! We’re creating some noise for the other subscribers of this ticket.)

In an attempt to turn this conversation back from “You’re Reading The Documentation Wrong” to “--enable and --disable Flags Are *Way* More Convenient Than Config Files For Ad-Hoc Workflows” I offer the following gross hack _*clever*_wrapper_script_ [N.B., “clever” is *not* a compliment, when it comes to software… «grin»]

prompt% less ~/bin/svgo.sh

#!/usr/bin/env bash

###################################################################
###  Helper: deref "/path/with/symliks" ==> /physical/location  ###
###################################################################

function deref() (
  [[ -n "${1:-}" ]] || return 1

  local rc=0 top="$(pwd)" target=""
  for target in "$@"; do
    [[ -n ${target:-} ]] || { ((++rc)); continue; }

    builtin cd "$top"
    local dir="" retval="" orig="$target"
    local counter=0

    #  NOTE: readlink(1) is not defined by POSIX, but has been shown to
    #  work on at least MacOS X, CentOS, Rocky, Ubuntu, openSUSE, and OpenBSD

    while [[ -L "${target}" ]]; do
          (( counter++ < 30 )) || { ((++rc)); continue 2; }
          if [[ ${target:-} == */* ]]; then
             dir="${target%/*}"
             if [[ -d ${dir:-/} ]]; then builtin cd -P "${dir:-/}" 2>/dev/null || { ((++rc)); continue 2; }; fi
          fi

          local link=""; link="$(readlink "${target##*/}")"
          local new_target=""; new_target="$([[ $link == /* ]] && echo "$link" \
                                      || { [[ $(pwd -P) = / ]] && echo "/$link" || echo "$(pwd -P)/$link"; })"
          target="$new_target"
    done

    if   [[ -z ${target:-} ]]; then retval="$(pwd -P)";
    elif [[ -d ${target:-} ]]; then builtin cd -P "$target" 2>/dev/null || { ((++rc)); continue; }; retval="$(pwd -P)";
    else retval="$(builtin cd -P "${target%/*}" 2>/dev/null \
           && { echo "$(p="$(pwd -P)"; echo "${p%/}")/${target##*/}"; } \
           || { echo "$([[ $target != /* ]] && echo "$(pwd -P)/")$target"; } )"
    fi

    if [[ -e $retval ]]
       then [[ $retval =~ (.*)/\.\.?$ ]] && echo "${BASH_REMATCH[1]}" || echo "$retval"
       else ((++rc))
    fi
  done

  return "${rc:-0}"
)


########################
###  --------------  ###
###  ---  svgo  ---  ###
###  --------------  ###
########################

function svgo() (
  _ARGS=()
  local   _CONFIG=()
  local  _ENABLED=()
  local _DISABLED=()

  export  SVGO_COMMAND;  : "${SVGO_COMMAND:="$(type -P svgo)"}"
  [[ -f "$SVGO_COMMAND"  ]] || { printf "\e[31;1mSVGO_COMMAND=\"%s\" command not found\e[m\n" "$SVGO_COMMAND" >&2; exit 1; }
  [[ ${DEBUG:-0} -le 0   ]] || { printf "\e[32;2mSVGO_COMMAND=\"%s\" == %s\e[m\n" "$SVGO_COMMAND" "$(deref "$SVGO_COMMAND")"; }

  export  SVGO_ROOT_DIR; : "${SVGO_ROOT_DIR:="$(dirname "$(dirname "$(deref "$SVGO_COMMAND")")")"}"
  [[ -d "$SVGO_ROOT_DIR" ]] || { printf "\e[31;1mSVGO_ROOT_DIR=\"%s\" not found\e[m\n" "$SVGO_ROOT_DIR" >&2; exit 1; }
  [[ ${DEBUG:-0} -le 0   ]] || { printf "\e[32;2mSVGO_ROOT_DIR=\"%s\"\e[m\n" "$SVGO_ROOT_DIR"; }

  while [[ $# -ge 1 ]]; do
      if   [[ "$1" =   "--"      ]]; then     _ARGS+=("$@"); break
      elif [[ "$1" =  "--config" ]]; then   _CONFIG+=("$2"); shift 2
      elif [[ "$1" =  "--enable" ]]; then  _ENABLED+=("$2"); shift 2
      elif [[ "$1" = "--disable" ]]; then _DISABLED+=("$2"); shift 2
      else _ARGS+=("$1"); shift
      fi
  done

  set -- ${_ARGS[@]+"${_ARGS[@]}"}

  if   [[ ${#_CONFIG[@]} -ge 1 ]] && { [[ ${#_ENABLED[@]} -ge 1 ]] || [[ ${#_DISABLED[@]} -ge 1 ]]; }
       then echo -e "\e[31;1m'--config <file>' is incompatible with '--{enabled/disabled} <plugin>'\e[m" >&2; exit 1
  elif [[ ${#_CONFIG[@]} -ge 2 ]]
       then echo -e "\e[33;1mMultiple '--config <file>' options detected; the last one will overwrite previous entries...\e[m" >&2
  fi

  local _DEFAULTS=($(node <<'END_OF_NODEJS'
  (async function(){
    const $SVGO_ROOT_DIR = process.env['SVGO_ROOT_DIR']

    const fs = require('fs')
    const isFile = async (file) => {
      try {
        const stats = await fs.promises.stat(file);
        return stats.isFile();
      } catch {
        return false;
      }
    };

    if ( config = ( await isFile(`${$SVGO_ROOT_DIR}/lib/svgo/config.js`) &&
         await require($SVGO_ROOT_DIR).loadConfig(`${$SVGO_ROOT_DIR}/lib/svgo/config.js`) ) )
       config.defaultPlugins.forEach(plugin => console.log(plugin))

    else if ( config = ( await isFile(`${$SVGO_ROOT_DIR}/plugins/preset-default.js`) &&
              await require($SVGO_ROOT_DIR).loadConfig(`${$SVGO_ROOT_DIR}/plugins/preset-default.js`) ) )
       config.plugins.forEach(plugin => console.log(plugin.name))
  })()
END_OF_NODEJS
  ))

  [[ ${DEBUG:-0} -le 0 ]] || echo -e "\e[2;1mDEFAULT PLUGINS:\e[m\n\e[2m${_DEFAULTS[@]}\e[m" >&2

  local _TMP=("${_ENABLED[@]}"); _ENABLED=()
  for i in "${_TMP[@]}"; do
    for j in "${_DEFAULTS[@]}"; do
      local seen=0; if [[ "$i" == "$j" ]]; then seen=1; break; fi
    done
    [[ $seen -ge 1 ]] || _ENABLED+=("$i")
  done

  local _TMP=("${_DISABLED[@]}"); _DISABLED=()
  for i in "${_TMP[@]}"; do
    for j in "${_DEFAULTS[@]}"; do
      local seen=0; if [[ "$i" == "$j" ]]; then seen=1; break; fi
    done
    [[ $seen -eq 0 ]] || _DISABLED+=("$i")
  done

  export  ENABLED="$(IFS=':'; echo  "${_ENABLED[*]}")"
  export DISABLED="$(IFS=':'; echo "${_DISABLED[*]}")"

  local SVGO_CONFIG="$(echo "module.exports = $( perl -e '
    use JSON::PP;
    my $plugins = [];
    push @$plugins =>
      { name => "preset-default", params => { overrides => { map { $_ => JSON::false } split /:/, ( $ENV{DISABLED} // "" ) } } },
      split /:/, ( $ENV{ENABLED} // "" );
    print JSON::PP->new->utf8->canonical->encode({ plugins => $plugins });
  ' )")"

  if (( ${#_CONFIG[@]} ))
     then "$SVGO_COMMAND" "$@" --config "${_CONFIG[@]: -1}"
     else [[ ${VERBOSE:-0} -le 0 ]] || echo -e "\e[34;1m$SVGO_CONFIG\e[m"
          "$SVGO_COMMAND" "$@" --config <(echo "$SVGO_CONFIG")
  fi
)

[[ ${__LOAD_ONLY:-0} -ge 1 ]] || svgo "$@"

PS — Yadita yadita, “No warranties, no copyrights, and no ifs, ands, or buts…” etc. ;-D

If it’s helps, SVGO no longer needs to be installed in the local scope. Doing npm i -g svgo/yarn global add svgo is fine. As for configuring SVGO, currently the recommended way is to create an svgo.config.mjs with a default export like:

export default {
  plugins: […]
}

Then, if it’s in the same directory, use SVGO as normal and it will detect the file. Or if it’s the config file is stored elsewhere, reference the config file with the --config argument.

svgo --config path/to/svgo.config.mjs file.svg

This means:

  1. It doesn’t pollute the local scope with node_modules.
  2. It’s still simple to configure. (Though I appreciate that to disable a plugin the configuration is quite verbose at the moment.)

If this isn’t desirable, I’d still be reluctant to bring back --enable and --disable because I don’t think it makes sense with how SVGO is designed today. There aren’t obvious expectations on how enabling plugins would work.

  • Does it replace default-preset? Or operate as well as default-preset?
  • If the plugin is already in default-preset, will we ignore it, or run it twice, once as part of default-preset and then again afterward?
  • In what order will enabled plugins be run relative to preset-default?
  • I assume the expectation is that if either --enable or --disable were specified, then we’d skip seeking an svgo.config.mjs file, or would you want --disable to still use the svgo.config.mjs file but without the specified plugin?

While we could define these things, I prefer how unambiguous and unassuming the current configuration is. SVGO config is more like a pipeline, and pipelines aren’t simply configured by turning things on or off. Things like order and options matter.

I would however be willing to add an argument like --plugins that allows one to specify the plugins property as it would be defined in svgo.config.mjs, but in the CLI without having to create a file on disk. We already have a CLI option for most of the options present in svgo.config.mjs anyway, just not one to define the plugins property. As for precedence, the explicit CLI option (--plugin) would take priority over whatever is defined in svgo.config.mjs (plugins), similarly to the behavior we already have for all other options.

Examples:

# use one plugin
svgo file.svg --plugins '["removeHiddenElems"]'

# use default plugins plus enable one more plugin to run after preset-default
svgo file.svg --plugins '["preset-default", "removeViewBox"]'

# run preset-default but exclude one of the plugins
svgo file.svg --plugins '[{"name": "preset-default", "params": {"overrides": {"removeHiddenElems": false}}}]'

Disabling a plugin is a little verbose, but otherwise:

  • This should be very simple to maintain on our side.
  • Has predictable behavior relative to svgo.config.mjs, so this should be intuitive enough to use.
  • Supports parameters, arrays, etc, unlike flags like --enable. (However, still no JavaScript functions or custom plugins.)

How would the participants of this issue feel about that?

Came here because of this as well. Looks like there is no way to use svgo if I just want to use it as a CLI program (without e.g. polluting local scope with node_modules created from npm i svgo). It’s probably better to remove CLI usage at all then as it’s so limited now.