implement --launcher

This commit is contained in:
Rich Harris
2018-05-03 23:04:05 -04:00
parent 7303e811be
commit d7a9074c69
3 changed files with 49 additions and 3 deletions

View File

@@ -21,9 +21,18 @@ prog.command('dev')
prog.command('build [dest]')
.describe('Create a production-ready version of your app')
.action(async (dest = 'build') => {
.option('-l, --launcher', 'Create a launcher file (defaults to start.js)')
.option('-p, --port', 'Default port, if using --launcher')
.example(`build -l`)
.example(`build custom-dir -l custom-launcher.js -p 4567`)
.action(async (dest = 'build', opts: { launcher: string | true, port: string }) => {
console.log(`> Building...`);
if (opts.port && !opts.launcher) {
console.error(`${clorox.bold.red(`You can only use the --port option with --launcher`)}`);
process.exit(1);
}
process.env.NODE_ENV = 'production';
process.env.SAPPER_DEST = dest;
@@ -32,7 +41,31 @@ prog.command('build [dest]')
try {
const { build } = await import('./cli/build');
await build();
console.error(`\n> Finished in ${elapsed(start)}. Type ${clorox.bold.cyan(dest === 'build' ? 'npx sapper start' : `npx sapper start ${dest}`)} to run the app.`);
let cmd;
if (opts.launcher) {
const launcher = opts.launcher === true ? 'start.js' : opts.launcher;
const resolvedLauncher = path.resolve(launcher);
const resolvedDest = path.resolve(dest);
const relative = path.relative(path.dirname(resolvedLauncher), resolvedDest);
fs.writeFileSync(resolvedLauncher, `
// generated by sapper build at ${new Date().toISOString()}
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
process.env.SAPPER_DEST = require('path').resolve(__dirname, '${relative}');
process.env.PORT = process.env.PORT || ${opts.port || 3000};
console.log('Starting server on port ' + process.env.PORT);
require('${relative[0] === '.' ? relative : `./${relative}`}/server.js');
`.replace(/^\t+/gm, '').trim());
cmd = `node ${path.relative(process.cwd(), launcher)}`;
} else {
cmd = dest === 'build' ? 'npx sapper start' : `npx sapper start ${dest}`;
}
console.error(`\n> Finished in ${elapsed(start)}. Type ${clorox.bold.cyan(cmd)} to run the app.`);
} catch (err) {
console.error(err ? err.details || err.stack || err.message || err : 'Unknown error');
}