This commit is contained in:
2022-07-18 02:50:52 +00:00
parent befd344ab0
commit 06181b34d6
8569 changed files with 818704 additions and 352705 deletions
+124 -147
View File
@@ -1,129 +1,92 @@
/*!
* @nuxt/generator v2.13.3 (c) 2016-2020
* - All the amazing contributors
* Released under the MIT License.
* @nuxt/generator v2.15.8 (c) 2016-2021
* Released under the MIT License
* Repository: https://github.com/nuxt/nuxt.js
* Website: https://nuxtjs.org
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
const path = _interopDefault(require('path'));
const chalk = _interopDefault(require('chalk'));
const consola = _interopDefault(require('consola'));
const fsExtra = _interopDefault(require('fs-extra'));
const htmlMinifier = _interopDefault(require('html-minifier'));
const path = require('path');
const chalk = require('chalk');
const consola = require('consola');
const devalue = require('devalue');
const fsExtra = require('fs-extra');
const defu = require('defu');
const htmlMinifier = require('html-minifier');
const nodeHtmlParser = require('node-html-parser');
const ufo = require('ufo');
const utils = require('@nuxt/utils');
function _typeof(obj) {
"@babel/helpers - typeof";
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function isObject(val) {
return val !== null && _typeof(val) === 'object' && !Array.isArray(val);
}
function _defu(baseObj, defaults) {
if (!isObject(baseObj)) {
return _defu({}, defaults);
}
if (!isObject(defaults)) {
return _defu(baseObj, {});
}
var obj = Object.assign({}, defaults);
for (var key in baseObj) {
if (key === '__proto__' || key === 'constructor') {
continue;
}
var val = baseObj[key];
if (val === null) {
continue;
}
if (isObject(val) && isObject(obj[key])) {
obj[key] = _defu(val, obj[key]);
} else {
obj[key] = val;
}
}
return obj;
}
function defu() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return args.reduce(_defu, {});
}
var defu_1 = defu;
const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
const chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
const devalue__default = /*#__PURE__*/_interopDefaultLegacy(devalue);
const fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
const defu__default = /*#__PURE__*/_interopDefaultLegacy(defu);
const htmlMinifier__default = /*#__PURE__*/_interopDefaultLegacy(htmlMinifier);
class Generator {
constructor (nuxt, builder) {
this.nuxt = nuxt;
this.options = nuxt.options;
this.builder = builder;
this.isFullStatic = false;
// Set variables
this.staticRoutes = path.resolve(this.options.srcDir, this.options.dir.static);
this.srcBuiltPath = path.resolve(this.options.buildDir, 'dist', 'client');
this.isFullStatic = utils.isFullStatic(this.options);
if (this.isFullStatic) {
consola__default['default'].info(`Full static generation activated`);
}
this.staticRoutes = path__default['default'].resolve(this.options.srcDir, this.options.dir.static);
this.srcBuiltPath = path__default['default'].resolve(this.options.buildDir, 'dist', 'client');
this.distPath = this.options.generate.dir;
this.distNuxtPath = path.join(
this.distNuxtPath = path__default['default'].join(
this.distPath,
utils.isUrl(this.options.build.publicPath) ? '' : this.options.build.publicPath
);
// Payloads for full static
if (this.isFullStatic) {
const { staticAssets, manifest } = this.options.generate;
this.staticAssetsDir = path__default['default'].resolve(this.distNuxtPath, staticAssets.dir, staticAssets.version);
this.staticAssetsBase = utils.urlJoin(this.options.app.cdnURL, this.options.generate.staticAssets.versionBase);
if (manifest) {
this.manifest = defu__default['default'](manifest, {
routes: []
});
}
}
// Shared payload
this._payload = null;
this.setPayload = (payload) => {
this._payload = defu_1(payload, this._payload);
this._payload = defu__default['default'](payload, this._payload);
};
}
async generate ({ build = true, init = true } = {}) {
consola.debug('Initializing generator...');
consola__default['default'].debug('Initializing generator...');
await this.initiate({ build, init });
// Payloads for full static
if (this.isFullStatic) {
consola.info('Full static mode activated');
const { staticAssets } = this.options.generate;
this.staticAssetsDir = path.resolve(this.distNuxtPath, staticAssets.dir, staticAssets.version);
this.staticAssetsBase = this.options.generate.staticAssets.versionBase;
}
consola.debug('Preparing routes for generate...');
consola__default['default'].debug('Preparing routes for generate...');
const routes = await this.initRoutes();
consola.info('Generating pages');
consola__default['default'].info('Generating pages' + (this.isFullStatic ? ' with full static mode' : ''));
const errors = await this.generateRoutes(routes);
await this.afterGenerate();
// Save routes manifest for full static
if (this.manifest) {
await this.nuxt.callHook('generate:manifest', this.manifest, this);
const manifestPath = path__default['default'].join(this.staticAssetsDir, 'manifest.js');
await fsExtra__default['default'].ensureDir(this.staticAssetsDir);
await fsExtra__default['default'].writeFile(manifestPath, `__NUXT_JSONP__("manifest.js", ${devalue__default['default'](this.manifest)})`, 'utf-8');
consola__default['default'].success('Static manifest generated');
}
// Done hook
await this.nuxt.callHook('generate:done', this, errors);
await this.nuxt.callHook('export:done', this, { errors });
@@ -145,23 +108,13 @@ class Generator {
// Start build process
await this.builder.build();
this.isFullStatic = utils.isFullStatic(this.options);
} else {
const hasBuilt = await fsExtra.exists(path.resolve(this.options.buildDir, 'dist', 'server', 'client.manifest.json'));
const hasBuilt = await fsExtra__default['default'].exists(path__default['default'].resolve(this.options.buildDir, 'dist', 'server', 'client.manifest.json'));
if (!hasBuilt) {
const fullStaticArgs = utils.isFullStatic(this.options) ? ' --target static' : '';
throw new Error(
`No build files found in ${this.srcBuiltPath}.\nPlease run \`nuxt build${fullStaticArgs}\` before calling \`nuxt export\``
`No build files found in ${this.srcBuiltPath}.\nPlease run \`nuxt build\``
)
}
const config = this.getBuildConfig();
if (!config || (config.target !== utils.TARGETS.static && !this.options._legacyGenerate)) {
throw new Error(
`In order to use \`nuxt export\`, you need to run \`nuxt build --target static\``
)
}
this.isFullStatic = config.isFullStatic;
this.options.render.ssr = config.ssr;
}
// Initialize dist directory
@@ -180,7 +133,7 @@ class Generator {
...args
);
} catch (e) {
consola.error('Could not resolve routes');
consola__default['default'].error('Could not resolve routes');
throw e // eslint-disable-line no-unreachable
}
}
@@ -189,7 +142,13 @@ class Generator {
if (this.options.router.mode === 'hash') {
routes = ['/'];
} else {
routes = utils.flatRoutes(this.getAppRoutes());
try {
routes = utils.flatRoutes(this.getAppRoutes());
} catch (err) {
// Case: where we use custom router.js
// https://github.com/nuxt-community/router-module/issues/83
routes = ['/'];
}
}
routes = routes.filter(route => this.shouldGenerateRoute(route));
routes = this.decorateWithPayloads(routes, generateRoutes);
@@ -212,14 +171,14 @@ class Generator {
getBuildConfig () {
try {
return require(path.join(this.options.buildDir, 'nuxt/config.json'))
return utils.requireModule(path__default['default'].join(this.options.buildDir, 'nuxt/config.json'))
} catch (err) {
return null
}
}
getAppRoutes () {
return require(path.join(this.options.buildDir, 'routes.json'))
return utils.requireModule(path__default['default'].join(this.options.buildDir, 'routes.json'))
}
async generateRoutes (routes) {
@@ -229,7 +188,7 @@ class Generator {
this.generatedRoutes = new Set();
routes.forEach(({ route, ...props }) => {
route = decodeURI(route);
route = decodeURI(this.normalizeSlash(route));
this.routes.push({ route, ...props });
// Add routes to the tracked generated routes (for crawler)
this.generatedRoutes.add(route);
@@ -261,12 +220,12 @@ class Generator {
const isHandled = type === 'handled';
const color = isHandled ? 'yellow' : 'red';
let line = chalk[color](` ${route}\n\n`);
let line = chalk__default['default'][color](` ${route}\n\n`);
if (isHandled) {
line += chalk.grey(JSON.stringify(error, undefined, 2) + '\n');
line += chalk__default['default'].grey(JSON.stringify(error, undefined, 2) + '\n');
} else {
line += chalk.grey(error.stack || error.message || `${error}`);
line += chalk__default['default'].grey(error.stack || error.message || `${error}`);
}
return line
@@ -282,11 +241,11 @@ class Generator {
return
}
const fallbackPath = path.join(this.distPath, fallback);
const fallbackPath = path__default['default'].join(this.distPath, fallback);
// Prevent conflicts
if (await fsExtra.exists(fallbackPath)) {
consola.warn(`SPA fallback was configured, but the configured path (${fallbackPath}) already exists.`);
if (await fsExtra__default['default'].exists(fallbackPath)) {
consola__default['default'].warn(`SPA fallback was configured, but the configured path (${fallbackPath}) already exists.`);
return
}
@@ -299,53 +258,57 @@ class Generator {
try {
html = this.minifyHtml(html);
} catch (error) {
consola.warn('HTML minification failed for SPA fallback');
consola__default['default'].warn('HTML minification failed for SPA fallback');
}
await fsExtra.writeFile(fallbackPath, html, 'utf8');
consola.success('Client-side fallback created: `' + fallback + '`');
await fsExtra__default['default'].writeFile(fallbackPath, html, 'utf8');
consola__default['default'].success('Client-side fallback created: `' + fallback + '`');
}
async initDist () {
// Clean destination folder
await fsExtra.emptyDir(this.distPath);
await fsExtra__default['default'].emptyDir(this.distPath);
consola.info(`Generating output directory: ${path.basename(this.distPath)}/`);
consola__default['default'].info(`Generating output directory: ${path__default['default'].basename(this.distPath)}/`);
await this.nuxt.callHook('generate:distRemoved', this);
await this.nuxt.callHook('export:distRemoved', this);
// Copy static and built files
if (await fsExtra.exists(this.staticRoutes)) {
await fsExtra.copy(this.staticRoutes, this.distPath);
if (await fsExtra__default['default'].exists(this.staticRoutes)) {
await fsExtra__default['default'].copy(this.staticRoutes, this.distPath);
}
// Copy .nuxt/dist/client/ to dist/_nuxt/
await fsExtra.copy(this.srcBuiltPath, this.distNuxtPath);
await fsExtra__default['default'].copy(this.srcBuiltPath, this.distNuxtPath);
if (this.payloadDir) {
await fsExtra.ensureDir(this.payloadDir);
await fsExtra__default['default'].ensureDir(this.payloadDir);
}
// Add .nojekyll file to let GitHub Pages add the _nuxt/ folder
// https://help.github.com/articles/files-that-start-with-an-underscore-are-missing/
const nojekyllPath = path.resolve(this.distPath, '.nojekyll');
fsExtra.writeFile(nojekyllPath, '');
const nojekyllPath = path__default['default'].resolve(this.distPath, '.nojekyll');
await fsExtra__default['default'].writeFile(nojekyllPath, '');
await this.nuxt.callHook('generate:distCopied', this);
await this.nuxt.callHook('export:distCopied', this);
}
normalizeSlash (route) {
return this.options.router && this.options.router.trailingSlash ? ufo.withTrailingSlash(route) : ufo.withoutTrailingSlash(route)
}
decorateWithPayloads (routes, generateRoutes) {
const routeMap = {};
// Fill routeMap for known routes
routes.forEach((route) => {
routeMap[route] = { route, payload: null };
routeMap[route] = { route: this.normalizeSlash(route), payload: null };
});
// Fill routeMap with given generate.routes
generateRoutes.forEach((route) => {
// route is either a string or like { route : '/my_route/1', payload: {} }
const path = utils.isString(route) ? route : route.route;
routeMap[path] = {
route: path,
route: this.normalizeSlash(path),
payload: route.payload || null
};
});
@@ -356,13 +319,15 @@ class Generator {
let html;
const pageErrors = [];
route = this.normalizeSlash(route);
const setPayload = (_payload) => {
payload = defu_1(_payload, payload);
payload = defu__default['default'](_payload, payload);
};
// Apply shared payload
if (this._payload) {
payload = defu_1(payload, this._payload);
payload = defu__default['default'](payload, this._payload);
}
await this.nuxt.callHook('generate:route', { route, setPayload });
@@ -378,33 +343,38 @@ class Generator {
// If crawler activated and called from generateRoutes()
if (this.options.generate.crawler && this.options.render.ssr) {
const possibleTrailingSlash = this.options.router.trailingSlash ? '/' : '';
nodeHtmlParser.parse(html).querySelectorAll('a').map((el) => {
const sanitizedHref = (el.getAttribute('href') || '')
.replace(this.options.router.base, '/')
.replace(/\/+$/, '')
.split('?')[0]
.split('#')[0]
.replace(/\/+$/, '')
.trim();
const route = decodeURI(sanitizedHref + possibleTrailingSlash);
const foundRoute = decodeURI(this.normalizeSlash(sanitizedHref));
if (route.startsWith('/') && !path.extname(route) && this.shouldGenerateRoute(route) && !this.generatedRoutes.has(route)) {
this.generatedRoutes.add(route);
this.routes.push({ route });
if (foundRoute.startsWith('/') && !foundRoute.startsWith('//') && !path__default['default'].extname(foundRoute) && this.shouldGenerateRoute(foundRoute) && !this.generatedRoutes.has(foundRoute)) {
this.generatedRoutes.add(foundRoute);
this.routes.push({ route: foundRoute });
}
return null
});
}
// Save Static Assets
if (this.staticAssetsDir && renderContext.staticAssets) {
for (const asset of renderContext.staticAssets) {
const assetPath = path.join(this.staticAssetsDir, asset.path);
await fsExtra.ensureDir(path.dirname(assetPath));
await fsExtra.writeFile(assetPath, asset.src, 'utf-8');
const assetPath = path__default['default'].join(this.staticAssetsDir, decodeURI(asset.path));
await fsExtra__default['default'].ensureDir(path__default['default'].dirname(assetPath));
await fsExtra__default['default'].writeFile(assetPath, asset.src, 'utf-8');
}
// Add route to manifest (only if no error and redirect)
if (this.manifest && (!res.error && !res.redirected)) {
this.manifest.routes.push(ufo.withoutTrailingSlash(route));
}
}
// SPA fallback
if (res.error) {
pageErrors.push({ type: 'handled', route, error: res.error });
}
@@ -414,7 +384,7 @@ class Generator {
await this.nuxt.callHook('generate:routeFailed', { route, errors: pageErrors });
await this.nuxt.callHook('export:routeFailed', { route, errors: pageErrors });
consola.error(this._formatErrors(pageErrors));
consola__default['default'].error(this._formatErrors(pageErrors));
return false
}
@@ -431,35 +401,42 @@ class Generator {
let fileName;
if (this.options.generate.subFolders) {
fileName = path.join(route, path.sep, 'index.html'); // /about -> /about/index.html
fileName = fileName === '/404/index.html' ? '/404.html' : fileName; // /404 -> /404.html
fileName = route === '/404'
? path__default['default'].join(path__default['default'].sep, '404.html') // /404 -> /404.html
: path__default['default'].join(route, path__default['default'].sep, 'index.html'); // /about -> /about/index.html
} else {
const normalizedRoute = route.replace(/\/$/, '');
fileName = route.length > 1 ? path.join(path.sep, normalizedRoute + '.html') : path.join(path.sep, 'index.html');
fileName = route.length > 1 ? path__default['default'].join(path__default['default'].sep, normalizedRoute + '.html') : path__default['default'].join(path__default['default'].sep, 'index.html');
}
// Call hook to let user update the path & html
const page = { route, path: fileName, html, exclude: false };
const page = {
route,
path: fileName,
html,
exclude: false,
errors: pageErrors
};
page.page = page; // Backward compatibility for export:page hook
await this.nuxt.callHook('generate:page', page);
await this.nuxt.callHook('export:page', { page, errors: pageErrors });
if (page.exclude) {
return false
}
page.path = path.join(this.distPath, page.path);
page.path = path__default['default'].join(this.distPath, page.path);
// Make sure the sub folders are created
await fsExtra.mkdirp(path.dirname(page.path));
await fsExtra.writeFile(page.path, page.html, 'utf8');
await fsExtra__default['default'].mkdirp(path__default['default'].dirname(page.path));
await fsExtra__default['default'].writeFile(page.path, page.html, 'utf8');
await this.nuxt.callHook('generate:routeCreated', { route, path: page.path, errors: pageErrors });
await this.nuxt.callHook('export:routeCreated', { route, path: page.path, errors: pageErrors });
if (pageErrors.length) {
consola.error(`Error generating route "${route}": ${pageErrors.map(e => e.error.message).join(', ')}`);
consola__default['default'].error(`Error generating route "${route}": ${pageErrors.map(e => e.error.message).join(', ')}`);
errors.push(...pageErrors);
} else {
consola.success(`Generated route "${route}"`);
consola__default['default'].success(`Generated route "${route}"`);
}
return true
@@ -472,7 +449,7 @@ class Generator {
// TODO: Remove in Nuxt version 3
if (typeof this.options.generate.minify !== 'undefined') {
minificationOptions = this.options.generate.minify;
consola.warn('generate.minify has been deprecated and will be removed in the next major version.' +
consola__default['default'].warn('generate.minify has been deprecated and will be removed in the next major version.' +
' Use build.html.minify instead!');
}
@@ -480,7 +457,7 @@ class Generator {
return html
}
return htmlMinifier.minify(html, minificationOptions)
return htmlMinifier__default['default'].minify(html, minificationOptions)
}
}