UNPKG

2.34 kBJavaScriptView Raw
1const chokidar = require('chokidar');
2const path = require('path');
3const child_process = require('child_process');
4const utils = require('../utils');
5const ora = require('ora');
6let port = 9999;
7
8function runner() {
9 const spinner = ora('').start();
10
11 const ydocPath = path.resolve(path.dirname(__dirname), '../bin/ydoc')
12 child_process.exec(`node ${ydocPath} build --mode=dev`, function(error, stdout, stderr){
13 spinner.stop()
14 if(error) throw error;
15 if(stdout) process.stdout.write(stdout);
16 if(stderr) process.stdout.write(stderr);
17 utils.log.ok('Starting up http-server: http://127.0.0.1:' + port)
18 })
19}
20
21function preventDuplication(time = 500) {
22 let sign = true;
23 return function (fn, ...arg) {
24 if (sign === false) return;
25 sign = false;
26 setTimeout(function () {
27 sign = true;
28 fn.apply(this, arg);
29 }, time)
30 }
31}
32
33function init() {
34 const ydocPath = path.resolve(__dirname, '../..')
35 const paths = [
36 path.resolve(ydocPath, './src'),
37 path.resolve(ydocPath, './theme')
38 ]
39
40 const projectPath = utils.projectPath;
41 const configFilepath = utils.getConfigPath(projectPath);
42 const config = utils.getConfig(configFilepath);
43 config.root = config.root || utils.defaultDocsPath;
44 config.root = path.resolve(projectPath, config.root);
45 const buildPath = config.dist || utils.defaultBuildPath;
46 paths.push(config.root);
47 if (configFilepath) paths.push(configFilepath)
48 return {
49 paths: paths,
50 buildPath: path.resolve(projectPath, buildPath)
51 };
52}
53
54function server(buildPath){
55 const Koa = require('koa');
56 var liveload = require('../live-reload');
57 const app = new Koa();
58 app.use(liveload(buildPath))
59 app.use(require('koa-static')(buildPath));
60 app.listen(port);
61}
62
63module.exports = {
64 setOptions: function (yargs) {
65 yargs.option('port', {
66 describe: 'Port of server',
67 default: 9999
68 })
69 },
70 run: function (argv) {
71 let preventDuplicationRunner = preventDuplication()
72 port = argv.port;
73
74 let config = init()
75 runner()
76 server(config.buildPath)
77
78 chokidar.watch(config.paths, {
79 ignoreInitial: true
80 }).on('all', () => {
81 config = init()
82 preventDuplicationRunner(runner)
83 })
84 },
85 desc: 'Starts a local server. By default, this is at http://127.0.0.1:' + port
86}
\No newline at end of file