Search code examples
svgwebpacknode-modulesyarnpkgloader

parsing SVG in webpack


I have created a project on Symfony 5. I am receiving an error in webpack when I run 'yarn build'. I am trying to fix it from few days but without success, so I decided to ask for some help :)

This is the error I am getting: enter image description here

I have enabled postCssLoader in my webpack.config and created postss.config.js in my root directory

.enablePostCssLoader()

postss.config.js File

module.exports = {
plugins: [
    require('autoprefixer'),
    require('postcss-svgo'),
    require('postcss-inline-svg'),
    require('postcss-write-svg'),
  ]
}

And here is a sample of svg I am trying to write in my css

.custom-checkbox .custom-control-input:checked~.custom-control-label::after {
background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'8\' 
     height=\'8\' viewBox=\'0 0 8 8\'%3e%3cpath fill=\'%23fff\' d=\'M6.564.75l-3.59 3.612-1.538- 
     1.55L0 4.26l2.974 2.99L8 2.193z\'/%3e%3c/svg%3e')
}

Solution

  • If the error transfers code verbatim, then there are two line breaks (and indentation) that makes the property invalid (see "CRLF": ..width=\'8\'CRLF height.. - this one you can backslash-escape in CSS, and ..1.538-CRLF 1.55L.. - this one with indentation separates numeral making path data invalid - you have to remove all whitespace between minus and digit). If this is it, simply removing line breaks (and suprefluous whitespace) should fix it:

    background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'8\' height=\'8\' viewBox=\'0 0 8 8\'%3e%3cpath fill=\'%23fff\' d=\'M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z\'/%3e%3c/svg%3e')
    

    If code snippet you provided is not directly from your source code, then you have probably some formarrter breaking it in the process (?)


    N.B. you don't usually have to escape SVG datauris so much, you could go with url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8' fill='%23fff'><path d='M6.564.75l-3.59 3.612-1.538-1.55L0 4.26l2.974 2.99L8 2.193z'/></svg>") (i.e. the only escaped sequence is #->%23) and most interpreters should pick it up just fine. I'm not sure about your build stack, but I'd guess that "safe over-escaped format for obsolete IEs" could be produced as the build result; and if you use preprocessor you can embed 'dataurized' external resources, what could prevent such formatting accidents. (Ah, that's probably what the postcss-inline-svg is doing for you.)