loading...

Gridsome g-images with dynamic paths

jeremyjackson89 profile image Jeremy Jackson ・1 min read

I've seen other people with this issue. Here's what has been working for me.

Go to gridsome.config.js and add an alias for your images folder inside of the chainWebpack function (you may need to add it):

module.exports = {
  siteName: 'Jeremy Jackson',
  plugins: [],
  chainWebpack: config => {
    config.resolve.alias.set('@images', '@/assets/images')
  },
  templates: {}
}

Save the file and restart the server.

Then in your code where you want to use the image you can do:

<g-image :src="require(`!!assets-loader!@images/${imageUrl}`)"/>

And the dynamic image shows up. This works inside of v-for as well.

For reference, here's the code I'm using inside of a v-for in my site:

<div id="project-images">
  <div class="section-header">Screenshots</div>
  <div class="row">
    <div 
      class="col-xs-12 col-sm-3 project-image"
      v-for="(projectImage, index) in $page.project.images"
      :key="projectImage"
      @click="openLightBox(index)"
    >
      <g-image class="responsive-image" :src="require(`!!assets-loader!@images/${projectImage}`)"/>
    </div>
  </div>
</div>

and the result:

project screenshots

This has worked for me. If there's a better solution to this, let me know so I can fix my stuff ;)

Discussion

markdown guide
 

Thanks for this tip! It worked for me, but webpack-bundle-analyzer revealed that all the image references were bloating my JS bundle.

I don't know of a better alternative for loading dynamic paths in g-image. What I decided to do instead is pre-process my source to add the paths I need. My source is all markdown, so I'm just adding an extra field to my frontmatter. I'd rather not have a field that could be derived from other frontmatter fields, but I can't find a better solution without degrading performance.

 

Gridsome total noob here - a couple of questions:

  • Is 'assets-loader' something that is built into gridsome? If not, where do I find it (no plugin I can find, google search isn't giving me anything)

  • Where does the '$page' and '$page.project' variable come from? I presume that's from a page-query. Is the 'project' member something you provided or is that inherent in gs?

 

Can you please explain how does Gridsome handles External Image Url in a Markdown File. Does it downloads the image or Simmply renders an External Image using that URL.

 

Hi, does this work with remote images as well? Will they be downloaded and transformed etc?