|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const connect = require('connect') |
| 4 | +const serveStatic = require('serve-static') |
| 5 | +const Renderer = require('docsify-server-renderer') |
| 6 | +const fs = require('fs') |
| 7 | +const util = require('../util/index') |
| 8 | +const chalk = require('chalk') |
| 9 | + |
| 10 | +var defaultConfig = { |
| 11 | + template: `<!DOCTYPE html> |
| 12 | +<html lang="en"> |
| 13 | +<head> |
| 14 | + <meta charset="UTF-8"> |
| 15 | + <title>My Doc</title> |
| 16 | + <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> |
| 17 | + <link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css" title="vue"> |
| 18 | +</head> |
| 19 | +<body> |
| 20 | + <!--inject-app--> |
| 21 | + <!--inject-config--> |
| 22 | +<script src="//unpkg.com/docsify/lib/docsify.min.js"></script> |
| 23 | +</body> |
| 24 | +</html>`, |
| 25 | + path: './' |
| 26 | +} |
| 27 | + |
| 28 | +function loadConfig (config) { |
| 29 | + try { |
| 30 | + return require(util.cwd(config)) |
| 31 | + } catch (e) { |
| 32 | + console.log(chalk.red(`Not found ${config}`)) |
| 33 | + process.exit(1) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +module.exports = function (path, configFile, port) { |
| 38 | + let config = defaultConfig |
| 39 | + const pkg = util.pkg() |
| 40 | + |
| 41 | + if (configFile) { |
| 42 | + config = loadConfig(configFile) |
| 43 | + } else if (pkg.docsify) { |
| 44 | + config = pkg.docsify |
| 45 | + config.template = util.exists(util.cwd(pkg.docsify.template)) |
| 46 | + ? util(pkg.docsify.template) |
| 47 | + : defaultConfig.template |
| 48 | + } |
| 49 | + |
| 50 | + var renderer = new Renderer(config) |
| 51 | + var server = connect() |
| 52 | + |
| 53 | + server.use(function(req, res) { |
| 54 | + renderer.renderToString(req.url) |
| 55 | + .then(res.end(html)) |
| 56 | + .catch(res.end(util.read(util.resolve(path, 'index.html')))) |
| 57 | + }) |
| 58 | + server.use(serveStatic(path || '.')) |
| 59 | + server.listen(port || 4000) |
| 60 | + |
| 61 | + const msg = '\n' |
| 62 | + + chalk.blue('[SSR]') |
| 63 | + + ' Serving ' + chalk.green(`${path}`) + ' now.\n' |
| 64 | + + 'Listening at ' + chalk.green(`http://localhost:${port}`) + '\n' |
| 65 | + |
| 66 | + console.log(msg) |
| 67 | +} |
0 commit comments