This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
module.ts
178 lines (156 loc) · 5.98 KB
/
module.ts
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
170
171
172
173
174
175
176
177
178
import { addVitePlugin, addWebpackPlugin, defineNuxtModule, addTemplate, resolveAlias, useNuxt, addPluginTemplate, logger, updateTemplates } from '@nuxt/kit'
import { isAbsolute, join, relative, resolve, normalize } from 'pathe'
import { createUnimport, Import, scanDirExports, toImports, Unimport } from 'unimport'
import { ImportsOptions, ImportPresetWithDeprecation } from '@nuxt/schema'
import defu from 'defu'
import { TransformPlugin } from './transform'
import { defaultPresets } from './presets'
export default defineNuxtModule<Partial<ImportsOptions>>({
meta: {
name: 'imports',
configKey: 'imports'
},
defaults: {
autoImport: true,
presets: defaultPresets,
global: false,
imports: [],
dirs: [],
transform: {
include: [],
exclude: undefined
}
},
async setup (options, nuxt) {
// TODO: remove deprecation warning
// @ts-ignore
if (nuxt.options.autoImports) {
logger.warn('`autoImports` config is deprecated, use `imports` instead.')
// @ts-ignore
options = defu(nuxt.options.autoImports, options)
}
// TODO: fix sharing of defaults between invocations of modules
const presets = JSON.parse(JSON.stringify(options.presets)) as ImportPresetWithDeprecation[]
// Allow modules extending sources
await nuxt.callHook('imports:sources', presets)
for (const _i of presets) {
const i = _i as ImportPresetWithDeprecation | string
if (typeof i !== 'string' && i.names && !i.imports) {
i.imports = i.names
logger.warn('imports: presets.names is deprecated, use presets.imports instead')
}
}
// Filter disabled sources
// options.sources = options.sources.filter(source => source.disabled !== true)
// Create a context to share state between module internals
const ctx = createUnimport({
presets,
imports: options.imports,
virtualImports: ['#imports'],
addons: {
vueTemplate: options.autoImport
}
})
// composables/ dirs from all layers
let composablesDirs: string[] = []
for (const layer of nuxt.options._layers) {
composablesDirs.push(resolve(layer.config.srcDir, 'composables'))
composablesDirs.push(resolve(layer.config.srcDir, 'utils'))
for (const dir of (layer.config.imports?.dirs ?? [])) {
if (!dir) {
continue
}
composablesDirs.push(resolve(layer.config.srcDir, dir))
}
}
await nuxt.callHook('imports:dirs', composablesDirs)
composablesDirs = composablesDirs.map(dir => normalize(dir))
// Support for importing from '#imports'
addTemplate({
filename: 'imports.mjs',
getContents: async () => await ctx.toExports() + '\nif (process.dev) { console.warn("[nuxt] `#imports` should be transformed with real imports. There seems to be something wrong with the imports plugin.") }'
})
nuxt.options.alias['#imports'] = join(nuxt.options.buildDir, 'imports')
// Transpile and injection
if (nuxt.options.dev && options.global) {
// Add all imports to globalThis in development mode
addPluginTemplate({
filename: 'imports.mjs',
getContents: async () => {
const imports = await ctx.getImports()
const importStatement = toImports(imports)
const globalThisSet = imports.map(i => `globalThis.${i.as} = ${i.as};`).join('\n')
return `${importStatement}\n\n${globalThisSet}\n\nexport default () => {};`
}
})
} else {
// Transform to inject imports in production mode
addVitePlugin(TransformPlugin.vite({ ctx, options, sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client }))
addWebpackPlugin(TransformPlugin.webpack({ ctx, options, sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client }))
}
const regenerateImports = async () => {
ctx.clearDynamicImports()
await ctx.modifyDynamicImports(async (imports) => {
// Scan composables/
imports.push(...await scanDirExports(composablesDirs))
// Modules extending
await nuxt.callHook('imports:extend', imports)
})
}
await regenerateImports()
// Generate types
addDeclarationTemplates(ctx, options)
// Add generated types to `nuxt.d.ts`
nuxt.hook('prepare:types', ({ references }) => {
references.push({ path: resolve(nuxt.options.buildDir, 'types/imports.d.ts') })
references.push({ path: resolve(nuxt.options.buildDir, 'imports.d.ts') })
})
// Watch composables/ directory
const templates = [
'types/imports.d.ts',
'imports.d.ts',
'imports.mjs'
]
nuxt.hook('builder:watch', async (_, path) => {
const _resolved = resolve(nuxt.options.srcDir, path)
if (composablesDirs.find(dir => _resolved.startsWith(dir))) {
await updateTemplates({
filter: template => templates.includes(template.filename)
})
}
})
nuxt.hook('builder:generateApp', async () => {
await regenerateImports()
})
}
})
function addDeclarationTemplates (ctx: Unimport, options: Partial<ImportsOptions>) {
const nuxt = useNuxt()
// Remove file extension for benefit of TypeScript
const stripExtension = (path: string) => path.replace(/\.[a-z]+$/, '')
const resolved: Record<string, string> = {}
const r = ({ from }: Import) => {
if (resolved[from]) {
return resolved[from]
}
let path = resolveAlias(from)
if (isAbsolute(path)) {
path = relative(join(nuxt.options.buildDir, 'types'), path)
}
path = stripExtension(path)
resolved[from] = path
return path
}
addTemplate({
filename: 'imports.d.ts',
getContents: () => ctx.toExports(nuxt.options.buildDir)
})
addTemplate({
filename: 'types/imports.d.ts',
getContents: async () => '// Generated by auto imports\n' + (
options.autoImport
? await ctx.generateTypeDeclarations({ resolvePath: r })
: '// Implicit auto importing is disabled, you can use explicitly import from `#imports` instead.'
)
})
}