refactor: start cli command

This commit is contained in:
endiliey 2018-08-08 00:45:58 +08:00
parent 7a69cff30c
commit 1150c45f9b

View file

@ -1,114 +1,115 @@
const path = require('path'); const path = require('path');
const fs = require('fs-extra'); const fs = require('fs-extra');
const chalk = require('chalk'); const chalk = require('chalk');
const webpack = require('webpack'); const webpack = require('webpack');
const chokidar = require('chokidar'); const chokidar = require('chokidar');
const convert = require('koa-connect'); const convert = require('koa-connect');
const range = require('koa-range'); const range = require('koa-range');
const mount = require('koa-mount'); const mount = require('koa-mount');
const serveStatic = require('koa-static'); const serveStatic = require('koa-static');
const history = require('connect-history-api-fallback'); const history = require('connect-history-api-fallback');
const portfinder = require('portfinder'); const portfinder = require('portfinder');
const serve = require('webpack-serve'); const serve = require('webpack-serve');
const webpackNiceLog = require('webpack-nicelog'); const webpackNiceLog = require('webpack-nicelog');
const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin');
const load = require('../load'); const load = require('../load');
const createDevConfig = require('../webpack/dev'); const createDevConfig = require('../webpack/dev');
async function getPort(port) { async function getPort(reqPort) {
portfinder.basePort = parseInt(port, 10) || 3000; portfinder.basePort = parseInt(reqPort, 10) || 3000;
return await portfinder.getPortPromise(); const port = await portfinder.getPortPromise();
} return port;
}
module.exports = async function start(siteDir, cliOptions = {}) {
// Preprocess whole files as a prop module.exports = async function start(siteDir, cliOptions = {}) {
const props = await load(siteDir); // Process all related files as a prop
const props = await load(siteDir);
// (if enabled) live reload for any changes in file
if (!cliOptions.noWatch) { if (!cliOptions.noWatch) {
const reload = () => { const reload = () => {
load(siteDir).catch(err => { load(siteDir).catch(err => {
console.error(chalk.red(err.stack)); console.error(chalk.red(err.stack));
}); });
}; };
const docsRelativeDir = props.siteConfig.customDocsPath || 'docs'; const docsRelativeDir = props.siteConfig.customDocsPath || 'docs';
const fsWatcher = chokidar.watch( const fsWatcher = chokidar.watch(
[`../${docsRelativeDir}/**/*.md`, 'blog/**/*.md', 'siteConfig.js'], [`../${docsRelativeDir}/**/*.md`, 'blog/**/*.md', 'siteConfig.js'],
{ {
cwd: siteDir, cwd: siteDir,
ignoreInitial: true ignoreInitial: true
} }
); );
fsWatcher.on('add', reload); fsWatcher.on('add', reload);
fsWatcher.on('change', reload); fsWatcher.on('change', reload);
fsWatcher.on('unlink', reload); fsWatcher.on('unlink', reload);
fsWatcher.on('addDir', reload); fsWatcher.on('addDir', reload);
fsWatcher.on('unlinkDir', reload); fsWatcher.on('unlinkDir', reload);
} }
const port = await getPort(cliOptions.port); const port = await getPort(cliOptions.port);
const {baseUrl} = props; const {baseUrl} = props;
// resolve webpack config // resolve webpack config
let config = createDevConfig(props); let config = createDevConfig(props);
config.plugin('WebpackNiceLog').use(webpackNiceLog, [ config.plugin('WebpackNiceLog').use(webpackNiceLog, [
{ {
name: 'Munseo', name: 'Munseo',
onDone: () => { onDone: () => {
console.log( console.log(
`\n${chalk.blue('Development server available at ')}${chalk.cyan( `\n${chalk.blue('Development server available at ')}${chalk.cyan(
`http://localhost:${port}${baseUrl}` `http://localhost:${port}${baseUrl}`
)}` )}`
); );
} }
} }
]); ]);
config.plugin('html-webpack-plugin').use(HtmlWebpackPlugin, [ config.plugin('html-webpack-plugin').use(HtmlWebpackPlugin, [
{ {
inject: false, inject: false,
hash: true, hash: true,
template: path.resolve(__dirname, '../core/index.html'), template: path.resolve(__dirname, '../core/devTemplate.ejs'),
filename: 'index.html' filename: 'index.html',
} title: props.siteConfig.title
]); }
]);
// create compiler from generated webpack config
config = config.toConfig(); // create compiler from generated webpack config
const compiler = webpack(config); config = config.toConfig();
const compiler = webpack(config);
// webpack-serve
const nonExistentDir = path.resolve(__dirname, 'non-existent'); // webpack-serve
setTimeout(async () => { const nonExistentDir = path.resolve(__dirname, 'non-existent');
await serve( setTimeout(async () => {
{}, await serve(
{ {},
content: [nonExistentDir], {
compiler, content: [nonExistentDir],
open: false, compiler,
devMiddleware: { open: false,
logLevel: 'silent' devMiddleware: {
}, logLevel: 'silent'
hotClient: { },
port: port + 1, hotClient: {
logLevel: 'error' port: port + 1,
}, logLevel: 'error'
logLevel: 'error', },
port, logLevel: 'error',
add: (app, middleware, options) => { port,
const staticDir = path.resolve(siteDir, 'static'); add: app => {
if (fs.existsSync(staticDir)) { const staticDir = path.resolve(siteDir, 'static');
app.use(mount(baseUrl, serveStatic(staticDir))); if (fs.existsSync(staticDir)) {
} app.use(mount(baseUrl, serveStatic(staticDir)));
app.use(range); // enable range request https://tools.ietf.org/html/rfc7233 }
app.use( app.use(range); // enable range request https://tools.ietf.org/html/rfc7233
convert( app.use(
history({ convert(
rewrites: [{from: /\.html$/, to: '/'}] history({
}) rewrites: [{from: /\.html$/, to: '/'}]
) })
); )
} );
} }
); }
}, 1000); );
}; }, 1000);
};