用sapper構建一個博客

發現本身很久沒有寫博客了。以前在github開了一個倉庫,在倉庫的issue區寫一些內容。issue區體驗挺好的,能夠refer上項目代碼,也能夠追加評論。但我想本身寫一個博客,不須要不少花裏胡哨的功能,只對內容專一,極大的好處是,能夠爲所欲爲的編寫本身喜歡的頁面樣式。恰好最近有接觸了下svelte,就順帶的用sapper寫一個靜態頁面。javascript

實現須要用到的知識點/技術:css

  1. svelte
  2. sapper
  3. tailwindcss
  4. typescript

後面兩點非必須,能夠根據本身須要進行增減。html

思路

總體的思路比較簡單。java

sapper支持export出靜態文件,我只須要將靜態文件部署到一個靜態站點,首選的就是github pages。sapper導出export有一個好處:node

Static doesn't mean non-interactive — your Svelte components work exactly as they do normally, and you still get all the benefits of client-side routing and prefetching.

sapper默認的template就是一個blog,這不是恰好能夠拿來起手嘛!但默認的template的 blog內容是固定的數據,大體內容是一個js文件,export一個blog的array。git

export const [
  {
    title: '2020-06/build-blog.md',
    slug: '2020-06_build-blog', // 生成的路由路徑
    html: '<h1 id=\"用sapper構建一個博客\">用sapper構建一個博客</h1>'
  }
]

在sapper export以後,能夠在__sapper__/export/blog看到生成html靜態文件。也就意味着最後須要部署到github pages的目錄,就是__sapper__目錄啦。github

可若是要寫博客,那確定也優先選擇Markdown。typescript

因此須要解決的也就是將Markdown文件轉爲上面提到的js文件。npm

將Markdown轉爲js文件

須要用到Markedjs數組

使用也是簡單粗暴:

const marked = require('marked')
marked.setOptions({
  renderer: new marked.Renderer(),
  highlight: function(code, language) {
    const hljs = require('highlight.js')
    const validLanguage = hljs.getLanguage(language) ? language : 'plaintext'
    return hljs.highlight(validLanguage, code).value
  },
  // ...(more options)
});
marked(markdownString)

例如markdownString爲:

*hello world*

將會被轉爲:

<p><em>hello world</em></p>

知道用法以後,只須要經過fs文件操做,將目標的Markdown文件所有push進一個數組,最後將數組寫入一個js文件。

讀取Markdown並寫入文件

node對操做文件提供了readirreadFilewriteFile等函數。

其中核心的處理邏輯以下:

// 獲取全部文件
const getAllFiles = function (dirPath, arrayOfFiles) {
    files = fs.readdirSync(dirPath)
    arrayOfFiles = arrayOfFiles || []
    files.forEach(function (file) {
        if (fs.statSync(dirPath + "/" + file).isDirectory()) {
            arrayOfFiles = getAllFiles(dirPath + "/" + file, arrayOfFiles)
        } else {
            arrayOfFiles.push(path.join(dirPath, "/", file))
        }
    })
    return arrayOfFiles
}
// 將markdown轉爲js文件
const compile = () => {
    try {
        const dirs = getAllFiles('./') // 讀取全部文件
        const inPosts = [] // 文章數組
        for (let fileName of dirs) {
            if (/.md/.test(fileName)) {
                const fileData = fs.readFileSync(`./${fileName}`, 'utf-8') // markdown內容
                const fmData = fm(fileData) // 此處能夠忽略fm(fm是處理markdown front matter的,無關緊要)
                const rmSuffix = fileName.split('.')[0] // 移除文件名後綴
                inPosts.push({
                    title: fileName,
                    path: rmSuffix,
                    slug: rmSuffix.replace('/', '_'),
                    html: marked(fmData.body),
                    fmData
                })
            }
        }
        inPosts.forEach(post => {
            post.html = post.html.replace(/^\t{3}/gm, '');
        });
        const outPutContent = `export default ${JSON.stringify(inPosts)}`
        fs.writeFile('../routes/blog/_posts.js', outPutContent, err => {
            if (err) return console.log('生成post失敗', err)
            console.log('已生成_posts.js')
        })
    } catch (error) {
        console.error('error', error)
    }
}
const watcher = chokidar.watch('./')
watcher
    .on('all', () => {
        compile()
    })

部署到github pages

對於sapper,執行export命令生成靜態文件。

npm run export

__sapper__/export推送到倉庫的gh-pages分支。

git subtree push --prefix __sapper__/export origin gh-pages

最後在倉庫設置出將gh-pages分支設置爲部署分支就行了。

以上完成了從寫Markdown到能夠看到文章,後續頁面的編寫就能夠爲所欲爲啦!

結果

源碼 https://github.com/GzhiYi/sap...
部署Demo https://gzhiyi.top

相關文章
相關標籤/搜索