ken
ken

Reputation: 9013

Resolve webpack image source within Vue Component (within Vuepress)

I am using the latest Vuepress release (1.0.0-alpha.46) and have the docs configured off the root directory and have an assets folder where I store all my images.

Referencing these images in markdown is no problem. For instance:

![ ](../assets/foobar.jpg)

Works just fine even though Webpack is adding an alias to the image of something like assets/foobar.57589334.jpg. Sadly, things start to fall over when I use a Vue component in my Vuepress. In this case I'm simply adding this to my markdown file:

this is some markdown
<zoom-image src="../assets/foobar.jpg" />

But now I'm getting the string literal without webpack's postfix added. I know I could put the image into .vuepress/public but that seems wrong and may actually cache things in the service worker that I don't want to. In the docs it talks about how you can configure webpack with aliases and I thought I'd give that a try. I configured webpack in the .vuepress/config.js file:

configureWebpack: {
  resolve: {
    alias: {
      "@images": "assets"
    }
  }
},

and the MD is now:

this is some markdown
<zoom-image src="~@images/foobar.jpg" />

No errors but maybe not surprisingly the string literal was just passed into my component again. I thought maybe I could pull in some sort of export from webpack to force it to transform the image name but I've not gotten anything to work. Can anyone help?

Upvotes: 4

Views: 1159

Answers (2)

Luis Rivera
Luis Rivera

Reputation: 517

If for some reason you are not able to get it working with configureWebpack try with chainWebpack instead.

const path = require("path"); // Don't forget this

module.exports = {
  chainWebpack: config => {
    config.resolve.alias.set('@assets', path.resolve(__dirname, "../assets"))
  }
}

My structure

|-- .vuepress
|   |-- config.js
|-- assets
|   |-- foobar.jpg

Alias like ![My foobar](~@assets/foobar.jpg)

Upvotes: 1

li haochen
li haochen

Reputation: 55

Heellooooo there, if I got your point, my solution looks like below: the config.js is:

configureWebpack: {
  resolve: {
    alias: {
      "@assets": path.resolve(__dirname, '../assets')
    }
  }
},

and my file structure is:

|-- .vuepress
|   |-- config.js
|-- assets
|   |-- icon.png
|-- guide
|   |-- 1.md
|   |-- 2.md
|   |-- 3.md
|   |-- 4.md

And then use this alias like: ![icon](~@assets/icon.png)

Upvotes: 2

Related Questions