发现自己良久没有写博客了。之前在github开了一个仓库,在仓库的issue区写一些内容。issue区体验挺好的,能够refer上我的项目代码,也能够追加评论。但我想本人写一个博客,不须要很多花里胡哨的性能,只对内容专一,极大的益处是,能够得心应手的编写本人喜爱的页面款式。刚好最近有接触了下svelte,就顺带的用sapper写一个动态页面。

实现须要用到的知识点/技术:

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

前面两点非必须,能够依据本人须要进行增减。

思路

整体的思路比较简单。

sapper反对export出动态文件,我只须要将动态文件部署到一个动态站点,首选的就是github pages。sapper导出export有一个益处:

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。

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__目录啦。

可如果要写博客,那必定也优先选择Markdown。

所以须要解决的也就是将Markdown文件转为下面提到的js文件。

将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