Dynamic Import with Webpack

Asked

Viewed 55 times

1

In an application Vuejs template Webpack, I need to import a number of SVG’s according to a user’s parameters.

The SVG’s are fixed files, but are dynamically loaded into the application. If I import all the files at once, the bundle gets very big (around 13mb). I also could not use the dynamic import because in this case the import would be an expression, something like import(x) where x is the file name to be imported according to user parameters.

What would be the solution to this problem? How can I accomplish the Lazy load of a Asset according to user parameters?

  • You can serve that content by ajax?

  • It is a solution if it is not possible to perform this import

  • @Sergio, one problem I see with ajax is having to control the cache of this file once loaded... something that Dynamic import makes easier

1 answer

0


It is possible to realize the import of the archives inline through the svg-inline-loader in the Webpack. To avoid collision of imports svg in the archives CSS required to use configuration issuer. The webpack.base.config was like this:

{
  test: /\.(svg)(\?.*)?$/,
  issuer: /\.css$/,
  loader: 'url-loader',
  options: {
    limit: 10000,
    name: utils.assetsPath('img/[name].[hash:7].[ext]')
  }
},
{
  test: /\.svg(\?.*)?$/,
  loader: 'svg-inline-loader',
}

For the dynamic realization of import the following code snippet can be used

let fileName = 'foo.svg'

import(`./svg/${fileName}.svg`)
      .then(module => { ... } )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.