Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: exclude certain svg files from being packed into app.js

Tags:

webpack

I have a Vue.js application which is built with Webpack. I added a library with hundreds of SVG Flags. The scss file is quite small - and the flags are separate SVG files in a folder. When I build, Webpack puts all SVG files base64 encoded into app.js. In this special case this is counter productive, because it unnecessarily blows up the size of my app. I would rather like to load the flags from the SVG folder on demand, to keep my app small.

In App.vue

<style lang="scss">
  @import '~flag-icon-css/sass/flag-icon.scss';
</style>

My Webpack Config has been created with vue-cli. It is from here: https://github.com/coreui/coreui-free-vue-admin-template/blob/v1/Vue_Starter/build/webpack.base.conf.js

The build contains the Flag-SVG files in the img path - so this is fine. But the Flag-SVGs are loaded as data from webpack, not directly from the img directory.

like image 641
Gerfried Avatar asked Jul 25 '18 15:07

Gerfried


2 Answers

You should move those SVG files into the ./static folder - thus they won't be included in the bundle but will be directly copied to ./dist folder and you will have to reference them using absolute URLs.

like image 149
IVO GELOV Avatar answered Nov 15 '22 15:11

IVO GELOV


I had to add some exceptions for the flags directory:

original lines in configuration:

  {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
    },
  }         

modified lines in configuration:

  {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
    },
    exclude: [
        /\\node_modules\\flag-icon-css\\.*\.svg([\?\#].*)?$/,
    ]
  }, 
  {
    test: /\.(svg)(\?.*)?$/,
    loader: 'file-loader',
    options: {
      limit: 10000,
      name: utils.assetsPath('img/flags/[name].[ext]')
    },
    include: [
        /\\node_modules\\flag-icon-css\\.*\.(svg)(\?.*)?$/,
    ]
  },          

Now all SVG files are handled as before - except for the flags. They are loaded from img/flags/. The files will be automatically copied into this folder on build and served from there.

One interesting thing to note: As I am working on Windows my include/exclude paths contain back-slashes - it does not work with forward slashes as the regex is compared with the path on the disc.

like image 35
Gerfried Avatar answered Nov 15 '22 14:11

Gerfried