Express/Node.js环境下渲染Markdown文件时如何应用CSS样式
修复方案
1. 修正服务端代码(index.js)
主要修改点:移除路由内重复的静态资源声明、将Markdown内容转为HTML后传递给模板、修正文件路径拼接逻辑。
修正后代码:
const express = require('express'); const bodyparser = require('body-parser'); const marked = require('marked'); const fs = require('fs'); const path = require('path'); const app = express() // 全局静态资源声明只需要一次即可 app.use(express.static(__dirname + '/')); app.use(express.static('public')); app.use(bodyparser.urlencoded({extend:true})); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.set('views', __dirname); app.get('/article', (req,res)=> { const mdPath = path.join(__dirname, 'articles', 'article.md') fs.readFile(mdPath, 'utf8', function(err, data) { if(err) { console.log(err); return res.status(500).send('读取文章失败') } // 将Markdown转为HTML,传递给模板 const htmlContent = marked.parse(data); res.render('index.html', { result: htmlContent }); }); }); const PORT= process.env.PORT || 3000; app.listen(PORT, function(){ console.log('server is running on port ' + PORT); })
2. 修正HTML模板(index.html)
主要修改点:修正CSS引入方式、使用正确的EJS输出语法避免HTML内容被转义。
修正后代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- 引入CSS用link标签,不要用script标签 --> <link rel="stylesheet" href="/style.css"> </head> <body> <!-- 用<%- 输出非转义的HTML内容,<%= 会转义标签 --> <%- result %> </body> </html>
3. 编写CSS样式
在public目录下新建style.css文件,直接针对Markdown转译生成的HTML标签写样式即可,示例:
/* 全局样式 */ body { max-width: 800px; margin: 0 auto; padding: 20px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif; line-height: 1.6; } /* 标题样式 */ h1, h2, h3, h4 { margin-top: 24px; margin-bottom: 16px; font-weight: 600; line-height: 1.25; border-bottom: 1px solid #eee; padding-bottom: 8px; } /* 代码块样式 */ code { background: #f6f8fa; padding: 2px 6px; border-radius: 4px; font-family: monospace; } pre code { display: block; padding: 16px; overflow-x: auto; } /* 引用样式 */ blockquote { border-left: 4px solid #ddd; padding-left: 16px; color: #666; margin-left: 0; } /* 列表样式 */ ul, ol { padding-left: 2em; } li { margin: 4px 0; }
启动服务访问/article路径,就能看到带样式的Markdown渲染结果。
内容的提问来源于stack exchange,提问作者user17291930
相关产品推荐
相关产品推荐

