Demo for using Webpack require function for inline-ing SVGs with dynamic paths in Vue apps.
This approach was promoted in Laracast: Whatcha Working On Series - Episode 38 - How to Dynamically Inline SVG Files in Vue Components.
This repository is proof-of-concept, why this technique is generally a bad idea.
<div v-html="require(`@/assets/${file}.svg`)"></div>
Issue here is, that at build time your Vue variables are unknown* to Webpack, so it includes all SVG files** in app bundle and then uses only those, that are really required. This can significatly increase your build time and bundle size. Not to mention optimization techniques as Lazy Loading Routes*** won't be as effective, as they could be.
* Vue variables get populated when app runs in client (browser).
** All SVG files in directory (and all subdirectories), that matches static part of required path to file.
*** You don't need download (and parse) whole bundle with all SVGs, if user is only viewing 1 page, where are only few (possibly none) SVGs.
This issue wasn't covered in mentioned Laracast video above. So, if you want to use this approach, you need to have specific directory structure, where you need to have all used SVGs in one directory (or its subdirectories). If you have there some SVGs, that you are not currently using, they will end up in your app bundle too. Alternatively, this could be solved with excluding files by Webpack, e.g.: all SVG files starting with underscore.
Not to mention, if there is no static file extension defined (as there wasn't in Laracast video), Webpack will bundle (or atleast try to) all resources (e.g.: *.svg
, *.jpg
, *.png
and even *.ai
files). And if there are some *.js
files, this will result into crashing Webpack process in most cases.
Real world example:
Imagine having all Font-Awesome SVG icons symlinked from node_modules
into your assets
directory. Why? Because you don't like its provided Vue usage. Ofcourse, you use only few icons from this set in your project, but described behavior will include whole set into your app bundle...
# clone this repository
$ git clone https://github.com/oliverfindl/vue-webpack-require-demo.git <DIRECTORY>
# change directory
$ cd <DIRECTORY>
# install dependencies
$ npm install
# download vue art repository
$ npm run setup
# run develepment server
$ npm run serve
# build for production
$ npm run build
# run tests [no tests included]
$ npm run test
# lint code
$ npm run lint
# save generated webpack config to file
$ npm run inspect