shrpne / vue-inline-svg

Dynamically loads an SVG source and inline <svg> element so you can manipulate the style of it
MIT License
177 stars 22 forks source link

Problem with `:src="require(...)"` in component library (Rollup) #37

Closed ldtsch closed 2 years ago

ldtsch commented 2 years ago

I am writing a component library that uses SVGs imported dynamically, i.e. according to the documentation with a :src="require(path)" attribute. The library then gets bundled using Rollup, however, after including the library, the require function is not recognized. I am using Vue 3 and vue-inline-svg 3.1.0. Library code snippet:

...
<InlineSvg
  class="icon"
  width="32px"
  height="32px"
  :src="require(`@/assets/${item.image}`)"
></InlineSvg>
...

The library is then compiled by rollup with the following plugins

...
plugins: [
  vue(),
  peerDepsExternal(),
  scss(),
  commonjs()
]

When including this component in the application, it will then throw the error

Header.vue?8b41:99 Uncaught (in promise) ReferenceError: require is not defined
    at eval (Header.vue?8b41:99:1)
    at Proxy.renderFnWithContext (runtime-core.esm-bundler.js?d2dd:850:1)
    at Proxy.eval (vue-router.esm-bundler.js?ec2d:2158:1)
    at renderComponentRoot (runtime-core.esm-bundler.js?d2dd:893:1)
    at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js?d2dd:5030:1)
    at ReactiveEffect.run (reactivity.esm-bundler.js?89dc:167:1)
    at setupRenderEffect (runtime-core.esm-bundler.js?d2dd:5156:1)
    at mountComponent (runtime-core.esm-bundler.js?d2dd:4939:1)
    at processComponent (runtime-core.esm-bundler.js?d2dd:4897:1)
    at patch (runtime-core.esm-bundler.js?d2dd:4489:1)

Has anyone seen and solved this problem before?

Thanks and Cheers

shrpne commented 2 years ago

Hi! This issue is not related to vue-inline-svg. require is needed if you use vue-loader to handle asset's path in your .vue files.

You should consult vue-loader docs on how to properly handle assets paths.

According to this https://vue-loader.vuejs.org/guide/asset-url.html#transform-rules omitting require should work for you.