@nuxt/cli-edge
Version:
111 lines (106 loc) • 3.19 kB
JavaScript
/*!
* @nuxt/cli-edge v2.18.2-28661769.e265ef3 (c) 2016-2024
* Released under the MIT License
* Repository: https://github.com/nuxt/nuxt.js
* Website: https://nuxtjs.org
*/
'use strict';
const utilsEdge = require('@nuxt/utils-edge');
const index = require('./cli-index.js');
const banner = require('./cli-banner.js');
const fs = require('fs');
const path = require('path');
const consola = require('consola');
const connect = require('connect');
const serveStatic = require('serve-static');
const compression = require('compression');
const configEdge = require('@nuxt/config-edge');
require('exit');
require('chalk');
require('std-env');
require('wrap-ansi');
require('boxen');
require('minimist');
require('hookable');
require('defu');
require('semver');
require('execa');
require('pretty-bytes');
async function serve(cmd) {
const _config = await cmd.getNuxtConfig({ dev: false });
const options = configEdge.getNuxtConfig(_config);
try {
const buildConfig = utilsEdge.requireModule(path.join(options.buildDir, "nuxt/config.json"));
options.target = buildConfig.target;
} catch (err) {
}
const distStat = await fs.promises.stat(options.generate.dir).catch(() => {
});
const distPath = path.join(options.generate.dir.replace(process.cwd() + path.sep, ""), path.sep);
if (!distStat || !distStat.isDirectory()) {
throw new Error("Output directory `" + distPath + "` does not exist, please use `nuxt generate` before `nuxt start` for static target.");
}
const app = connect();
app.use(compression({ threshold: 0 }));
app.use(
options.router.base,
serveStatic(options.generate.dir, {
extensions: ["html"]
})
);
if (options.generate.fallback) {
const fallbackFile = await fs.promises.readFile(path.join(options.generate.dir, options.generate.fallback), "utf-8");
app.use((req, res, next) => {
const ext = path.extname(req.url) || ".html";
if (ext !== ".html") {
return next();
}
res.writeHeader(200, {
"Content-Type": "text/html"
});
res.write(fallbackFile);
res.end();
});
}
const { port, host, socket, https } = options.server;
const { Listener } = await index.server();
const listener = new Listener({
port,
host,
socket,
https,
app,
dev: true,
// try another port if taken
baseURL: options.router.base
});
await listener.listen();
const { Nuxt } = await index.core();
banner.showBanner({
constructor: Nuxt,
options,
server: {
listeners: [listener]
}
}, false);
consola.info(`Serving static application from \`${distPath}\``);
}
const start = {
name: "start",
description: "Start the application in production mode (the application should be compiled with `nuxt build` first)",
usage: "start <dir>",
options: {
...index.common,
...index.server$1
},
async run(cmd) {
const config = await cmd.getNuxtConfig({ dev: false, _start: true });
if (config.target === utilsEdge.TARGETS.static) {
return serve(cmd);
}
const nuxt = await cmd.getNuxt(config);
await nuxt.server.listen();
banner.showBanner(nuxt);
}
};
exports.default = start;