-
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathindex.ts
More file actions
169 lines (139 loc) · 5.83 KB
/
index.ts
File metadata and controls
169 lines (139 loc) · 5.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
import fs from 'fs'
import { dirname, resolve, relative } from 'pathe'
import chokidar from 'chokidar'
import type { Module } from '@nuxt/types/config'
import consola from 'consola'
import { requireNuxtVersion } from './compatibility'
import { scanComponents } from './scan'
import type { Options, ComponentsDir } from './types'
import { loader } from './loader'
const isPureObjectOrString = (val: any) => (!Array.isArray(val) && typeof val === 'object') || typeof val === 'string'
const getDir = (p: string) => fs.statSync(p).isDirectory() ? p : dirname(p)
const componentsModule: Module<Options> = function () {
const { nuxt } = this
const { components } = nuxt.options
/* istanbul ignore if */
if (!components) {
return
}
requireNuxtVersion(nuxt?.constructor?.version, '2.10')
const options: Options = {
dirs: ['~/components'],
loader: !nuxt.options.dev,
...Array.isArray(components) ? { dirs: components } : components
}
nuxt.hook('build:before', async (builder: any) => {
const nuxtIgnorePatterns: string[] = builder.ignore.ignore ? builder.ignore.ignore._rules.map((rule: any) => rule.pattern) : /* istanbul ignore next */ []
await nuxt.callHook('components:dirs', options.dirs)
const resolvePath = (dir: any) => nuxt.resolver.resolvePath(dir)
// Add components/global/ directory (backward compatibility to remove prefix)
try {
const globalDir = getDir(resolvePath('~/components/global'))
if (!options.dirs.find(dir => resolvePath(dir) === globalDir)) {
options.dirs.push({
path: globalDir
})
}
} catch (err) {
/* istanbul ignore next */
nuxt.options.watch.push(resolve(nuxt.options.srcDir, 'components', 'global'))
}
const componentDirs = options.dirs.filter(isPureObjectOrString).map((dir) => {
const dirOptions: ComponentsDir = 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 level
dirOptions.level = Number(dirOptions.level || 0)
const enabled = fs.existsSync(dirPath)
if (!enabled && dirOptions.path !== '~/components') {
// eslint-disable-next-line no-console
console.warn('Components directory not found: `' + dirPath + '`')
}
const extensions = dirOptions.extensions || builder.supportedExtensions
return {
...dirOptions,
enabled,
path: dirPath,
extensions,
pattern: dirOptions.pattern || `**/*.{${extensions.join(',')},}`,
isAsync: dirOptions.isAsync,
// TODO: keep test/unit/utils.ts updated
ignore: [
'**/*.stories.{js,ts,jsx,tsx}', // ignore storybook files
'**/*{M,.m,-m}ixin.{js,ts,jsx,tsx}', // ignore mixins
'**/*.d.ts', // .d.ts files
...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 scanComponents(componentDirs, nuxt.options.srcDir!)
await nuxt.callHook('components:extend', components)
// Add loader for tree shaking in production only
if (options.loader) {
// eslint-disable-next-line no-console
consola.info('Using components loader to optimize imports')
this.extendBuild((config) => {
const vueRule = config.module?.rules.find(rule => rule.test?.toString().includes('.vue'))
config.plugins = config.plugins || []
config.plugins.push(loader.webpack({
include: vueRule?.test as any,
findComponent (name) {
return components.find(component => component.kebabName === name || component.pascalName === name)
}
}) as any)
})
this.nuxt.hook('vite:extend', ({ config }: any) => {
config.plugins = config.plugins || []
config.plugins.push(loader.vite({
findComponent (name) {
return components.find(component => component.kebabName === name || component.pascalName === name)
}
}))
})
}
// 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 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',
'components/readme_md',
'vetur/tags.json'
]
for (const t of templates) {
this[t.includes('plugin') ? 'addPlugin' : 'addTemplate']({
src: resolve(__dirname, '../templates', t),
fileName: t.replace('_', '.'),
options: { getComponents }
})
}
// Add CLI info to inspect discovered components
const componentsListFile = resolve(nuxt.options.buildDir, 'components/readme.md')
// eslint-disable-next-line no-console
consola.info('Discovered Components:', relative(process.cwd(), componentsListFile))
})
}
// @ts-ignore
componentsModule.meta = { name: '@nuxt/components' }
export default componentsModule