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
+62 -29
View File
@@ -1,29 +1,62 @@
import { Module } from '@nuxt/types';
import { ScanDir } from './scan';
declare type componentsDirHook = (dirs: ComponentsDir[]) => void | Promise<void>;
declare type componentsExtendHook = (components: (ComponentsDir | ScanDir)[]) => void | Promise<void>;
declare module '@nuxt/types/config/hooks' {
interface NuxtOptionsHooks {
'components:dirs'?: componentsDirHook;
'components:extend'?: componentsExtendHook;
components?: {
dirs?: componentsDirHook;
extend?: componentsExtendHook;
};
}
}
export interface ComponentsDir extends ScanDir {
watch?: boolean;
extensions?: string[];
transpile?: 'auto' | boolean;
}
export interface Options {
dirs: (string | ComponentsDir)[];
}
declare module '@nuxt/types/config/index' {
interface NuxtOptions {
components: boolean | Options | Options['dirs'];
}
}
declare const componentsModule: Module<any>;
export default componentsModule;
import { Module } from '@nuxt/types/config';
interface Component {
pascalName: string;
kebabName: string;
import: string;
asyncImport: string;
export: string;
filePath: string;
shortPath: string;
isAsync?: boolean;
chunkName: string;
/** @deprecated */
global: boolean;
level: number;
prefetch: boolean;
preload: boolean;
}
interface ScanDir {
path: string;
pattern?: string | string[];
ignore?: string[];
prefix?: string;
isAsync?: boolean;
/** @deprecated */
global?: boolean | 'dev';
pathPrefix?: boolean;
level?: number;
prefetch?: boolean;
preload?: boolean;
extendComponent?: (component: Component) => Promise<Component | void> | (Component | void);
}
interface ComponentsDir extends ScanDir {
watch?: boolean;
extensions?: string[];
transpile?: 'auto' | boolean;
}
declare type componentsDirHook = (dirs: ComponentsDir[]) => void | Promise<void>;
declare type componentsExtendHook = (components: (ComponentsDir | ScanDir)[]) => void | Promise<void>;
interface Options {
dirs: (string | ComponentsDir)[];
loader: Boolean;
}
declare module '@nuxt/types/config/index' {
interface NuxtOptions {
components: boolean | Options | Options['dirs'];
}
}
declare module '@nuxt/types/config/hooks' {
interface NuxtOptionsHooks {
'components:dirs'?: componentsDirHook;
'components:extend'?: componentsExtendHook;
components?: {
dirs?: componentsDirHook;
extend?: componentsExtendHook;
};
}
}
declare const componentsModule: Module<Options>;
export { componentsModule as default };
+206 -127
View File
@@ -1,170 +1,249 @@
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
const fs = require('fs');
const path = require('upath');
const chokidar = require('chokidar');
const consola = require('consola');
const chalk = require('chalk');
const semver = require('semver');
const globby = require('globby');
const scule = require('scule');
var path = require('path');
var path__default = _interopDefault(path);
var fs = require('fs');
var fs__default = _interopDefault(fs);
var chokidar = _interopDefault(require('chokidar'));
var RuleSet = _interopDefault(require('webpack/lib/RuleSet'));
var chalk = _interopDefault(require('chalk'));
var semver = _interopDefault(require('semver'));
require('globby');
require('lodash');
var scan = require('./scan-aa06f603.js');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
const path__default = /*#__PURE__*/_interopDefaultLegacy(path);
const chokidar__default = /*#__PURE__*/_interopDefaultLegacy(chokidar);
const consola__default = /*#__PURE__*/_interopDefaultLegacy(consola);
const chalk__default = /*#__PURE__*/_interopDefaultLegacy(chalk);
const semver__default = /*#__PURE__*/_interopDefaultLegacy(semver);
const globby__default = /*#__PURE__*/_interopDefaultLegacy(globby);
function requireNuxtVersion(currentVersion, requiredVersion) {
const pkgName = require('../package.json').name;
const pkgName = require("../package.json").name;
if (!currentVersion || !requireNuxtVersion) {
return;
}
const _currentVersion = semver__default['default'].coerce(currentVersion);
const _requiredVersion = semver__default['default'].coerce(requiredVersion);
if (semver__default['default'].lt(_currentVersion, _requiredVersion)) {
throw new Error(`
const _currentVersion = semver.coerce(currentVersion);
${chalk__default['default'].cyan(pkgName)} is not compatible with your current Nuxt version : ${chalk__default['default'].yellow("v" + currentVersion)}
const _requiredVersion = semver.coerce(requiredVersion);
if (semver.lt(_currentVersion, _requiredVersion)) {
throw new Error(`\n
${chalk.cyan(pkgName)} is not compatible with your current Nuxt version : ${chalk.yellow('v' + currentVersion)}\n
Required: ${chalk.green('v' + requiredVersion)} or ${chalk.cyan('higher')}
Required: ${chalk__default['default'].green("v" + requiredVersion)} or ${chalk__default['default'].cyan("higher")}
`);
}
}
const isPureObjectOrString = val => !Array.isArray(val) && typeof val === 'object' || typeof val === 'string';
function sortDirsByPathLength({ path: pathA }, { path: pathB }) {
return pathB.split(/[\\/]/).filter(Boolean).length - pathA.split(/[\\/]/).filter(Boolean).length;
}
function hyphenate(str) {
return str.replace(/\B([A-Z])/g, "-$1").toLowerCase();
}
async function scanComponents(dirs, srcDir) {
const components = [];
const filePaths = new Set();
const scannedPaths = [];
for (const { path: path$1, pattern, ignore = [], prefix, extendComponent, pathPrefix, level, prefetch = false, preload = false, isAsync: dirIsAsync } of dirs.sort(sortDirsByPathLength)) {
const resolvedNames = new Map();
for (const _file of await globby__default['default'](pattern, { cwd: path$1, ignore })) {
const filePath = path.join(path$1, _file);
if (scannedPaths.find((d) => filePath.startsWith(d))) {
continue;
}
if (filePaths.has(filePath)) {
continue;
}
filePaths.add(filePath);
const prefixParts = [].concat(prefix ? scule.splitByCase(prefix) : [], pathPrefix !== false ? scule.splitByCase(path.relative(path$1, path.dirname(filePath))) : []);
let fileName = path.basename(filePath, path.extname(filePath));
if (fileName.toLowerCase() === "index") {
fileName = pathPrefix === false ? path.basename(path.dirname(filePath)) : "";
}
const isAsync = (fileName.endsWith(".async") ? true : dirIsAsync) || null;
fileName = fileName.replace(/\.async$/, "");
const fileNameParts = scule.splitByCase(fileName);
const componentNameParts = [];
while (prefixParts.length && (prefixParts[0] || "").toLowerCase() !== (fileNameParts[0] || "").toLowerCase()) {
componentNameParts.push(prefixParts.shift());
}
const componentName = scule.pascalCase(componentNameParts).replace(/^\d+/, "") + scule.pascalCase(fileNameParts).replace(/^\d+/, "");
if (resolvedNames.has(componentName)) {
console.warn(`Two component files resolving to the same name \`${componentName}\`:
const getDir = p => fs__default.statSync(p).isDirectory() ? p : path__default.dirname(p);
const componentsModule = function () {
var _nuxt$constructor;
const {
nuxt
} = this;
const {
components
} = nuxt.options;
- ${filePath}
- ${resolvedNames.get(componentName)}`);
continue;
}
resolvedNames.set(componentName, filePath);
const pascalName = scule.pascalCase(componentName);
const kebabName = hyphenate(componentName);
const shortPath = path.relative(srcDir, filePath);
const chunkName = "components/" + kebabName;
let component = {
filePath,
pascalName,
kebabName,
chunkName,
shortPath,
isAsync,
import: "",
asyncImport: "",
export: "default",
global: Boolean(global),
level: Number(level),
prefetch: Boolean(prefetch),
preload: Boolean(preload)
};
if (typeof extendComponent === "function") {
component = await extendComponent(component) || component;
}
component.import = component.import || `require('${component.filePath}').${component.export}`;
component.asyncImport = component.asyncImport || `function () { return import('${component.filePath}' /* webpackChunkName: "${component.chunkName}" */).then(function(m) { return m['${component.export}'] || m }) }`;
const definedComponent = components.find((c) => c.pascalName === component.pascalName);
if (definedComponent && component.level < definedComponent.level) {
Object.assign(definedComponent, component);
} else if (!definedComponent) {
components.push(component);
}
}
scannedPaths.push(path$1);
}
return components;
}
const isPureObjectOrString = (val) => !Array.isArray(val) && typeof val === "object" || typeof val === "string";
const getDir = (p) => fs__default['default'].statSync(p).isDirectory() ? p : path__default['default'].dirname(p);
const componentsModule = function() {
var _a;
const { nuxt } = this;
const { components } = nuxt.options;
if (!components) {
return;
}
requireNuxtVersion(nuxt === null || nuxt === void 0 ? void 0 : (_nuxt$constructor = nuxt.constructor) === null || _nuxt$constructor === void 0 ? void 0 : _nuxt$constructor.version, '2.10');
requireNuxtVersion((_a = nuxt == null ? void 0 : nuxt.constructor) == null ? void 0 : _a.version, "2.10");
const options = {
dirs: ['~/components'],
...(Array.isArray(components) ? {
dirs: components
} : components)
dirs: ["~/components"],
loader: !nuxt.options.dev,
...Array.isArray(components) ? { dirs: components } : components
};
nuxt.hook('build:before', async builder => {
const nuxtIgnorePatterns = builder.ignore.ignore ? builder.ignore.ignore._rules.map(rule => rule.pattern) :
/* istanbul ignore next */
[];
await nuxt.callHook('components:dirs', options.dirs);
const componentDirs = options.dirs.filter(isPureObjectOrString).map(dir => {
const dirOptions = typeof dir === 'object' ? dir : {
path: dir
};
nuxt.hook("build:before", async (builder) => {
const nuxtIgnorePatterns = builder.ignore.ignore ? builder.ignore.ignore._rules.map((rule) => rule.pattern) : [];
await nuxt.callHook("components:dirs", options.dirs);
const resolvePath = (dir) => nuxt.resolver.resolvePath(dir);
try {
const globalDir = getDir(resolvePath("~/components/global"));
if (!options.dirs.find((dir) => resolvePath(dir) === globalDir)) {
options.dirs.push({
path: globalDir
});
}
} catch (err) {
nuxt.options.watch.push(path__default['default'].resolve(nuxt.options.srcDir, "components", "global"));
}
const componentDirs = options.dirs.filter(isPureObjectOrString).map((dir) => {
const dirOptions = typeof dir === "object" ? dir : { path: dir };
let dirPath = dirOptions.path;
try {
dirPath = getDir(nuxt.resolver.resolvePath(dirOptions.path));
} catch (err) {}
const transpile = typeof dirOptions.transpile === 'boolean' ? dirOptions.transpile : 'auto'; // Normalize global option
if (dirOptions.global === 'dev') {
dirOptions.global = nuxt.options.dev;
} catch (err) {
}
const enabled = fs__default.existsSync(dirPath);
if (!enabled && dirOptions.path !== '~/components') {
// eslint-disable-next-line no-console
console.warn('Components directory not found: `' + dirPath + '`');
const transpile = typeof dirOptions.transpile === "boolean" ? dirOptions.transpile : "auto";
dirOptions.level = Number(dirOptions.level || 0);
const enabled = fs__default['default'].existsSync(dirPath);
if (!enabled && dirOptions.path !== "~/components") {
console.warn("Components directory not found: `" + dirPath + "`");
}
const extensions = dirOptions.extensions || builder.supportedExtensions;
return { ...dirOptions,
return {
...dirOptions,
enabled,
path: dirPath,
extensions,
pattern: dirOptions.pattern || `**/*.{${extensions.join(',')},}`,
ignore: nuxtIgnorePatterns.concat(dirOptions.ignore || []),
transpile: transpile === 'auto' ? dirPath.includes('node_modules') : transpile
pattern: dirOptions.pattern || `**/*.{${extensions.join(",")},}`,
isAsync: dirOptions.isAsync,
ignore: [
"**/*.stories.{js,ts,jsx,tsx}",
"**/*{M,.m,-m}ixin.{js,ts,jsx,tsx}",
"**/*.d.ts",
...nuxtIgnorePatterns,
...dirOptions.ignore || []
],
transpile: transpile === "auto" ? dirPath.includes("node_modules") : transpile
};
}).filter(d => d.enabled);
nuxt.options.build.transpile.push(...componentDirs.filter(dir => dir.transpile).map(dir => dir.path));
let components = await scan.scanComponents(componentDirs, nuxt.options.srcDir);
await nuxt.callHook('components:extend', components); // Add loader for tree shaking
if (componentDirs.some(dir => !dir.global)) {
this.extendBuild(config => {
const {
rules
} = new RuleSet(config.module.rules);
const vueRule = rules.find(rule => rule.use && rule.use.find(use => use.loader === 'vue-loader'));
}).filter((d) => d.enabled);
nuxt.options.build.transpile.push(...componentDirs.filter((dir) => dir.transpile).map((dir) => dir.path));
let components2 = await scanComponents(componentDirs, nuxt.options.srcDir);
await nuxt.callHook("components:extend", components2);
if (options.loader) {
consola__default['default'].info("Using components loader to optimize imports");
this.extendBuild((config) => {
var _a2;
const vueRule = (_a2 = config.module) == null ? void 0 : _a2.rules.find((rule) => {
var _a3;
return (_a3 = rule.test) == null ? void 0 : _a3.toString().includes(".vue");
});
if (!vueRule) {
throw new Error("Cannot find vue loader");
}
if (!vueRule.use) {
vueRule.use = [{
loader: vueRule.loader.toString(),
options: vueRule.options
}];
delete vueRule.loader;
delete vueRule.options;
}
if (!Array.isArray(vueRule.use)) {
vueRule.use = [vueRule.use];
}
vueRule.use.unshift({
loader: require.resolve('./loader'),
loader: require.resolve("./loader"),
options: {
dependencies: nuxt.options.dev ? componentDirs.filter(dir => !dir.global).map(dir => dir.path) :
/* istanbul ignore next */
[],
getComponents: () => components
getComponents: () => components2
}
});
config.module.rules = rules;
}); // Add Webpack entry for runtime installComponents function
nuxt.hook('webpack:config', configs => {
for (const config of configs.filter(c => ['client', 'modern', 'server'].includes(c.name))) {
config.entry.app.unshift(path__default.resolve(__dirname, '../lib/installComponents.js'));
}
});
} // Watch
// istanbul ignore else
if (nuxt.options.dev && componentDirs.some(dir => dir.watch !== false)) {
const watcher = chokidar.watch(componentDirs.filter(dir => dir.watch !== false).map(dir => dir.path), nuxt.options.watchers.chokidar);
watcher.on('all', async eventName => {
if (!['add', 'unlink'].includes(eventName)) {
return;
}
components = await scan.scanComponents(componentDirs, nuxt.options.srcDir);
await nuxt.callHook('components:extend', components);
await builder.generateRoutesAndFiles();
}); // Close watcher on nuxt close
nuxt.hook('close', () => {
watcher.close();
});
} // Global components
// Add templates
const getComponents = () => components;
const templates = ['components/index.js', 'components/plugin.js', 'vetur/tags.json'];
for (const t of templates) {
this[t.includes('plugin') ? 'addPlugin' : 'addTemplate']({
src: path__default.resolve(__dirname, '../templates', t),
fileName: t,
options: {
getComponents
nuxt.hook("webpack:config", (configs) => {
for (const config of configs.filter((c) => ["client", "modern", "server"].includes(c.name))) {
config.entry.app.unshift(path__default['default'].resolve(__dirname, "../lib/installComponents.js"));
}
});
}
if (nuxt.options.dev && componentDirs.some((dir) => dir.watch !== false)) {
const watcher = chokidar__default['default'].watch(componentDirs.filter((dir) => dir.watch !== false).map((dir) => dir.path), nuxt.options.watchers.chokidar);
watcher.on("all", async (eventName) => {
if (!["add", "unlink"].includes(eventName)) {
return;
}
components2 = await scanComponents(componentDirs, nuxt.options.srcDir);
await nuxt.callHook("components:extend", components2);
await builder.generateRoutesAndFiles();
});
nuxt.hook("close", () => {
watcher.close();
});
}
const getComponents = () => components2;
const templates = [
"components/index.js",
"components/plugin.js",
"components/readme_md",
"vetur/tags.json"
];
for (const t of templates) {
this[t.includes("plugin") ? "addPlugin" : "addTemplate"]({
src: path__default['default'].resolve(__dirname, "../templates", t),
fileName: t.replace("_", "."),
options: { getComponents }
});
}
const componentsListFile = path__default['default'].resolve(nuxt.options.buildDir, "components/readme.md");
consola__default['default'].info("Discovered Components:", path__default['default'].relative(process.cwd(), componentsListFile));
});
}; // @ts-ignore
componentsModule.meta = {
name: '@nuxt/components'
};
componentsModule.meta = { name: "@nuxt/components" };
module.exports = componentsModule;
+5 -2
View File
@@ -1,2 +1,5 @@
import { loader as WebpackLoader } from 'webpack';
export default function loader(this: WebpackLoader.LoaderContext, content: string): Promise<void>;
import { loader as loader$1 } from 'webpack';
declare function loader(this: loader$1.LoaderContext, content: string): Promise<void>;
export { loader as default };
+31 -52
View File
@@ -1,89 +1,68 @@
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
require('path');
var fs = require('fs');
var fs__default = _interopDefault(fs);
const fs = require('fs');
const vueTemplateCompiler = require('vue-template-compiler');
require('upath');
require('globby');
require('lodash');
var scan = require('./scan-aa06f603.js');
var loaderUtils = _interopDefault(require('loader-utils'));
var vueTemplateCompiler = require('vue-template-compiler');
require('scule');
async function extractTags(resourcePath) {
const tags = new Set();
const file = (await fs.readFileSync(resourcePath)).toString('utf8');
const file = (await fs.readFileSync(resourcePath)).toString("utf8");
const component = vueTemplateCompiler.parseComponent(file);
if (component.template) {
if (component.template.lang === 'pug') {
if (component.template.lang === "pug") {
try {
const pug = require('pug');
component.template.content = pug.render(component.template.content, {
filename: resourcePath
});
const pug = require("pug");
component.template.content = pug.render(component.template.content, { filename: resourcePath });
} catch (err) {
/* Ignore compilation errors, they'll be picked up by other loaders */
}
}
vueTemplateCompiler.compile(component.template.content, {
modules: [{
postTransformNode: el => {
postTransformNode: (el) => {
tags.add(el.tag);
}
}]
});
}
return [...tags];
}
function install(content, components) {
const imports = '{' + components.map(c => `${c.pascalName}: ${c.import}`).join(',') + '}';
let newContent = '/* nuxt-component-imports */\n';
newContent += `installComponents(component, ${imports})\n`; // Insert our modification before the HMR code
const hotReload = content.indexOf('/* hot reload */');
if (hotReload > -1) {
content = content.slice(0, hotReload) + newContent + '\n\n' + content.slice(hotReload);
} else {
content += '\n\n' + newContent;
}
return content;
function matcher(tags, components) {
return tags.reduce((matches, tag) => {
const match = components.find(({ pascalName, kebabName }) => [pascalName, kebabName].includes(tag));
match && matches.push(match);
return matches;
}, []);
}
function install(content, components) {
const imports = "{" + components.map((c) => `${c.pascalName}: ${c.isAsync ? c.asyncImport : c.import}`).join(",") + "}";
let newContent = "/* nuxt-component-imports */\n";
newContent += `installComponents(component, ${imports})
`;
const hotReload = content.indexOf("/* hot reload */");
if (hotReload > -1) {
content = content.slice(0, hotReload) + newContent + "\n\n" + content.slice(hotReload);
} else {
content += "\n\n" + newContent;
}
return content;
}
async function loader(content) {
this.async();
this.cacheable();
if (!this.resourceQuery) {
this.addDependency(this.resourcePath);
const {
dependencies,
getComponents
} = {
dependencies: [],
getComponents: () => [],
...loaderUtils.getOptions(this)
};
for (const dependency of dependencies) {
this.addDependency(dependency);
}
const { getComponents } = this.query;
const nonAsyncComponents = getComponents().filter((c) => c.isAsync !== true);
const tags = await extractTags(this.resourcePath);
const matchedComponents = scan.matcher(tags, getComponents());
const matchedComponents = matcher(tags, nonAsyncComponents);
if (matchedComponents.length) {
content = install.call(this, content, matchedComponents);
}
}
this.callback(null, content);
}