hexo引用本地圖片無法顯示
阿新 • • 發佈:2018-11-15
最近重新開始用起hexo,但是發現在文章中引用本地圖片時總是顯示不出來。
問題如下圖所示。
花費了許久時間才解決這個問題。
因此將一些解決經驗整理出來,希望能幫助到大家。
一、外掛安裝與配置
首先我們需要安裝一個圖片路徑轉換的外掛,這個外掛名字是hexo-asset-image
npm install https://github.com/CodeFalling/hexo-asset-image --save
但是這個外掛的內容需要修改【不然可能會出Bug】
開啟/node_modules/hexo-asset-image/index.js,將內容更換為下面的程式碼
'use strict';
var cheerio = require('cheerio');
// http://stackoverflow.com/questions/14480345/how-to-get-the-nth-occurrence-in-a-string
function getPosition(str, m, i) {
return str.split(m, i).join(m).length;
}
var version = String(hexo.version).split('.');
hexo.extend.filter.register('after_post_render' , function(data){
var config = hexo.config;
if(config.post_asset_folder){
var link = data.permalink;
if(version.length > 0 && Number(version[0]) == 3)
var beginPos = getPosition(link, '/', 1) + 1;
else
var beginPos = getPosition(link, '/', 3) + 1;
// In hexo 3.1.1, the permalink of "about" page is like ".../about/index.html".
var endPos = link.lastIndexOf('/') + 1;
link = link.substring(beginPos, endPos);
var toprocess = ['excerpt', 'more', 'content'];
for(var i = 0; i < toprocess.length; i++){
var key = toprocess[i];
var $ = cheerio.load(data[key], {
ignoreWhitespace: false,
xmlMode: false,
lowerCaseTags: false,
decodeEntities: false
});
$('img').each(function(){
if ($(this).attr('src')){
// For windows style path, we replace '\' to '/'.
var src = $(this).attr('src').replace('\\', '/');
if(!/http[s]*.*|\/\/.*/.test(src) &&
!/^\s*\//.test(src)) {
// For "about" page, the first part of "src" can't be removed.
// In addition, to support multi-level local directory.
var linkArray = link.split('/').filter(function(elem){
return elem != '';
});
var srcArray = src.split('/').filter(function(elem){
return elem != '' && elem != '.';
});
if(srcArray.length > 1)
srcArray.shift();
src = srcArray.join('/');
$(this).attr('src', config.root + link + src);
console.info&&console.info("update link as:-->"+config.root + link + src);
}
}else{
console.info&&console.info("no src attr, skipped...");
console.info&&console.info($(this));
}
});
data[key] = $.html();
}
}
});
開啟_config.yml檔案,修改下述內容
post_asset_folder: true
二、問題推測
(一)本地圖片沒有有效上傳至github倉庫中,導致引用無效
解決方案:安裝外掛(回看前文)
(二)本地圖片沒有存放在同名資料夾中
解決方案:將需要引用的本地圖片存放在與文章名相同的資料夾中
(三)圖片路徑出錯
這也是我出現的問題。
開啟F12,發現下圖問題。
因為我在github中關於Hexo的倉庫名為850552586.github.io,並不是Ericam.com,所以導致了訪問無效。
【這個問題可能是因為我更換電腦後重新配置Hexo忽略的地方】
解決方案:開啟_config.yml修改下述內容
(四)相對路徑引用的標籤外掛
通過常規的 markdown 語法和相對路徑來引用圖片和其它資源可能會導致它們在存檔頁或者主頁上顯示不正確。在Hexo 2時代,社群建立了很多外掛來解決這個問題。但是,隨著Hexo 3 的釋出,許多新的標籤外掛被加入到了核心程式碼中。這使得你可以更簡單地在文章中引用你的資源。
也就是說在存檔頁和主頁不能使用和文章內容中的常規語法來引用圖片。
比如說:當你開啟文章資原始檔夾功能後,你把一個 example.jpg
圖片放在了你的資原始檔夾中,如果通過使用相對路徑的常規 markdown 語法 ![](/example.jpg)
,它將 不會 出現在首頁上。(但是它會在文章中按你期待的方式工作)
正確的引用圖片方式是使用下列的標籤外掛而不是 markdown :
{% asset_img example.jpg This is an example image %}